Skip to content

Instantly share code, notes, and snippets.

@erikerlandson
Created May 19, 2014 21:33
Show Gist options
  • Save erikerlandson/83345520a1646167f749 to your computer and use it in GitHub Desktop.
Save erikerlandson/83345520a1646167f749 to your computer and use it in GitHub Desktop.
Demonstrate generic conversion, where explicit invocations work but implicit invocations don't happen
trait CastOptionToV[V] {
def cast[T:TypeTag](o:Option[T]):V
}
class CastOptionToLong extends CastOptionToV[Long] {
def cast[T:TypeTag](o:Option[T]):Long = {
val tLong = typeOf[Long]
typeOf[T] match {
case `tLong` => o.asInstanceOf[Option[Long]].get
case _ => throw new Exception
}
}
}
class CastOptionToString extends CastOptionToV[String] {
def cast[T:TypeTag](o:Option[T]):String = {
val tLong = typeOf[Long]
typeOf[T] match {
case `tLong` => o.asInstanceOf[Option[Long]].get.toString
case _ => throw new Exception
}
}
}
object CastVals {
implicit val CO2Long = new CastOptionToLong
implicit val CO2String = new CastOptionToString
}
import CastVals._
// I can call an explicit caster and it works
def explicitCast[V:CastOptionToV](o:Option[Long]):V = {
val caster = implicitly[CastOptionToV[V]]
caster.cast(o)
}
object Cast{
// This compiles fine, but it doesn't ever get invoked when it's wanted
implicit def implicitCaster[V:CastOptionToV](o:Option[Long]):V = {
val caster = implicitly[CastOptionToV[V]]
caster.cast(o)
}
}
import Cast._
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment