Scala - String in URL

My class Scala

requires a url. I could use a class String

, but I would like Java to be built into the url validation. What's the best way to let it take either a Java Url class or a String, and if String, turn it into a Java Url?

+3


source to share


2 answers


You can use an overloaded constructor or method apply

:

class A(id: Int, url: URL) {
    def this(id: Int, url: String) = this(id, new URL(url))
}

      



or

case class A(id: Int, url: URL)

object A {
    def apply(id: Int, url: String): A = new A(id, new URL(url))
}

      

+5


source


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.)

+4


source







All Articles