如何匹配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
(import
typeOf
from
universe
)@0\uuu,@senia
错误:对象运行时不是包reflect的成员。在2.9.x中,您应该使用。