Skip to content

Instantly share code, notes, and snippets.

@tpolecat
Last active December 12, 2015 03:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tpolecat/4710992 to your computer and use it in GitHub Desktop.
Save tpolecat/4710992 to your computer and use it in GitHub Desktop.
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"))
}
@sj-climber
Copy link

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment