[英]How to match scala generic type?
Is there any way to match just on generic type passed in function? 有没有办法只匹配函数中传递的泛型类型? I'd like to do: 我想这样做:
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)
}
I thought about something like classOf
or typeOf
, but none of them is acceptable for just types, but objects. 我想过像classOf
或typeOf
这样的东西,但是对于只是类型而言,它们都不是可接受的,而是对象。
My idea was also to create some object of type T
and then check its type, but I think there can be a better solution. 我的想法也是创建一个T
类型的对象,然后检查它的类型,但我认为可以有一个更好的解决方案。
You could use ClassTag
. 你可以使用ClassTag
。
val string = implicitly[ClassTag[String]]
def getValue[T : ClassTag] =
implicitly[ClassTag[T]] match {
case `string` => "String"
case ClassTag.Int => "Int"
case _ => "Other"
}
Or TypeTag
: 或TypeTag
:
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"
Usage: 用法:
scala> getValue[String]
res0: String = String
scala> getValue[Int]
res1: String = Int
scala> getValue[Long]
res2: String = Other
If you are using 2.9.x
you should use Manifest
: 如果你使用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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.