【问题标题】:How to match scala generic type?如何匹配scala泛型类型?
【发布时间】:2013-07-06 19:50:26
【问题描述】:

有什么方法可以只匹配传入函数的泛型类型吗? 我想做:

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 类型的对象,然后检查它的类型,但我认为可以有更好的解决方案。

【问题讨论】:

    标签: scala generics pattern-matching


    【解决方案1】:

    你可以使用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"
    

    【讨论】:

    • @PatrykĆwiek:可以在一些附加字段中存储类型信息,但它会破坏 Java 兼容性。无法避免 java 类型中的类型擦除。
    • 我知道,我知道。只是一厢情愿。也许我只是有点被 C#/F# 宠坏了。
    • @senia 你可以写typeOf[String] 而不是implicitly[TypeTag[String]].tpe (import typeOf from universe)
    • @0__, @senia error: object runtime is not a member of package reflect
    • @squixy:scalaVersion := "2.10.2"。在 2.9.x 中,您应该使用 Manifest
    猜你喜欢
    • 2013-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-09
    • 1970-01-01
    • 2014-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多