Last active
December 12, 2015 03:58
-
-
Save tpolecat/4710992 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package examples | |
object SJ extends App { | |
trait Getter[T] { | |
def get(s: String): Option[T] | |
} | |
def get[T: Getter](s: String, default: T): T = | |
implicitly[Getter[T]].get(s).getOrElse(default) | |
// another way to write 'get' | |
def get2[T](s: String, default: T)(implicit g: Getter[T]): T = | |
g.get(s).getOrElse(default) | |
implicit val getInt = new Getter[Int] { | |
def get(s: String): Option[Int] = | |
try { | |
Some(s.toInt) | |
} catch { | |
case _: NumberFormatException => None | |
} | |
} | |
implicit val getString = new Getter[String] { | |
def get(s: String): Option[String] = Option(s) | |
} | |
println(get("123", 456)) | |
println(get("foo", 456)) | |
println(get("foo", "bar")) | |
println(get(null, "baz")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Imagine get() is defined without the default, i.e.:
def get[[T: Getter]](s: String): T = ...
Now assume we have 2 case classes as follows:
case class A(a: String)
case class B(a: Int)
It looks like the types of the case class values aren't considered during type inference. In particular, the compiler complains of ambiguous implicit types with the following:
A(get("someString"))
B(get("someInt"))
Any ideas? Thanks!