这是我能做到的最好的。它不会捕获真正的运行时类型信息,这正是我想要的,但它至少在编译时捕获了使用点已知的类型信息:
import scala.reflect.runtime.universe._
trait Lover {
def love[ T : TypeTag ]( amour : T ) : String;
}
class TypedLover[MY_TYPE : TypeTag] {
def love[ T : TypeTag ]( amour : T ) : String =
if ( implicitly[TypeTag[T]].tpe <:< implicitly[TypeTag[MY_TYPE]].tpe )
"You are totally my type."
else
"Nope, sorry, not my type."
}
以下是它的工作原理:
scala> val intLover = new TypedLover[Int]
intLover: TypedLover[Int] = TypedLover@2d4cadc4
scala> intLover.love(7)
res2: String = You are totally my type.
scala> intLover.love("Hello")
res3: String = Nope, sorry, not my type.
scala> val stringLover = new TypedLover[String]
stringLover: TypedLover[String] = TypedLover@1f7c9157
scala> stringLover.love(7)
res4: String = Nope, sorry, not my type.
scala> stringLover.love("Hello")
res5: String = You are totally my type.
但它仍然无法捕获实际的运行时类型信息:
scala> val stringInAnyRef : Any = "Hello"
stringInAnyRef: Any = Hello
scala> stringLover.love( stringInAnyRef )
res7: String = Nope, sorry, not my type.
它并不完美,但它是迄今为止我所拥有的最好的。