如何匹配scala泛型类型?
是否有任何方法仅在传递到函数中的泛型类型上进行匹配? 我想做:如何匹配scala泛型类型?,scala,generics,pattern-matching,Scala,Generics,Pattern Matching,是否有任何方法仅在传递到函数中的泛型类型上进行匹配? 我想做: def getValue[T](cursor: Cursor, columnName: String): T = { val index = cursor.getColumnIndex(columnName) T match { case String => cursor.getString(index) case Int => cursor.getInteger(inde
def getValue[T](cursor: Cursor, columnName: String): T = {
val index = cursor.getColumnIndex(columnName)
T match {
case String => cursor.getString(index)
case Int => cursor.getInteger(index)
}
我考虑过像classOf
或typeOf
这样的东西,但它们都不能仅用于类型,而只能用于对象
我的想法也是创建一些类型为
T
的对象,然后检查其类型,但我认为可以有更好的解决方案。您可以使用ClassTag
val string = implicitly[ClassTag[String]]
def getValue[T : ClassTag] =
implicitly[ClassTag[T]] match {
case `string` => "String"
case ClassTag.Int => "Int"
case _ => "Other"
}
或类型标签
:
import scala.reflect.runtime.universe.{TypeTag, typeOf}
def getValue[T : TypeTag] =
if (typeOf[T] =:= typeOf[String])
"String"
else if (typeOf[T] =:= typeOf[Int])
"Int"
else
"Other"
用法:
scala> getValue[String]
res0: String = String
scala> getValue[Int]
res1: String = Int
scala> getValue[Long]
res2: String = Other
如果您使用的是2.9.x
,则应使用Manifest
:
import scala.reflect.Manifest
def getValue[T : Manifest] =
if (manifest[T] == manifest[String])
"String"
else if (manifest[T] == manifest[Int])
"Int"
else
"Other"
@PatrykĆwiek:可以在一些附加字段中存储类型信息,但这会破坏java兼容性。没有办法避免java类型中的类型擦除。我知道,我知道。只是一厢情愿。也许我只是被C#/F#宠坏了一点。@senia你可以写
typeOf[String]
而不是隐式地[TypeTag[String]].tpe
(importtypeOf
fromuniverse
)@0\uuu,@senia错误:对象运行时不是包reflect的成员。在2.9.x中,您应该使用。