如何匹配scala泛型?

时间:2013-07-09 09:09:59

标签: 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(index)
 }

我考虑过像classOftypeOf这样的东西,但它们都不是唯一可以接受的类型,而是对象。

我的想法也是创建一些T类型的对象,然后检查它的类型,但我认为可以有更好的解决方案。

1 个答案:

答案 0 :(得分:6)

您可以使用ClassTag

val string = implicitly[ClassTag[String]]
def getValue[T : ClassTag] =
  implicitly[ClassTag[T]] match {
    case `string` => "String"
    case ClassTag.Int => "Int"
    case _ => "Other"
  }

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"

用法:

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"