Scala - String in URL
You can create an implicit conversion from String
to URL
and only accept URL
(which is what you want anyway). implicit def
can be in companion class or in helper class / trait (trait in cake template). Something like that:
implicit def `string to url`(s: String) = new URL(s)
Using:
import the.helper.Container._
//or implement the Helper trait containing the implicit def
val url: URL = "http://google.com"
The downside is that exceptions can come from unexpected places (anyone can ask for more import
).
A less implicit approach would be to "add" a method toURL
to String
, for example:
object Helpers {
implicit class String2URL(s: String) {
def toURL = new URL(s)
}
}
Using this would look like:
import Helpers._
val aUrl = "http://google.com".toURL
Comparison with @ mz's answer: you can combine multiple parameters this way without blowing up the combination of different parameters, while for this answer it will be exponential (although for small exponents, for example, in this case 1
, it is perfectly ok), @mz's answer is not can be reused, if you need another class you need to re-create it. It works on the library side, so lib users get good documentation, guidance on how to use it, my work will only work with "magic" and / or a little user help (eg import
method, toURL
method call conversion). I would choose @mz's solution for small combinations especially with customization Option
orTry
... But if you need to overload multiple parameters, I think my solution works better. It really depends on your use case. (You can wrap mine with a help Try
if there might be cases where the passed url is invalid.)
source to share