Scala使用match匹配类型出现的unreachable code问题

def getAs[T >: Null](id: JsonElement, field: T): T = field  match {

    case s: Class[Long] => id.getAsLong.asInstanceOf[T]

    case s: Class[Int] => id.getAsInt.asInstanceOf[T]

    case s: Class[Float] =>     id.getAsFloat.asInstanceOf[T]

    case s: Class[String] =>  id.getAsString.asInstanceOf[T]

    case _ => throw new RuntimeException("cannot assign " + id + " to " + field)

  }

以上就是使用的代码。结果总出现unreachable code警告。后来在 http://www.scala-lang.org/old/node/1045  看到说明了。原来scala的类型变量(classOf)在编译以后是不带类型的,看下面的代码

val x = classOf[String]

scala> x.isInstanceOf[Class[String]]
warning: there were unchecked warnings; re-run with -unchecked for details
res3: Boolean = true

scala> x.isInstanceOf[Class[Int]]   
warning: there were unchecked warnings; re-run with -unchecked for details
res4: Boolean = true

 

这说明使用Class[_]或者是classOf[_]操作之后,所有的结果(比如Class[Int]或者classOf[String])都成为同一个类型。 这样,就没有办法进行模式匹配。(match操作其实匹配的是类型)

 

怎么解决这个问题:

用if else的方式

 val result = if(clz == classOf[String] )
        Some(rs getString name)
    else if(clz == classOf[Int] ){
        Some(rs getInt name)
    else if(clz == classOf[Date] )
        Some(rs getDate name)
     else None
     result map (_.asInstanceOf[T])

 

你可能感兴趣的:(scala)