Created
May 19, 2014 21:33
-
-
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
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
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