如何消除类型擦除警告?

时间:2014-04-24 16:31:56

标签: scala scala-2.10

我有这段代码,在每个使用abstract type pattern reflect.runtime.universe.MethodSymbol is unchecked since it is eliminated by erasure关键字的地方都会收到case警告。我觉得它对反射API有些奇怪。问题是,当我运行它时(通过和失败的代码路径)它都有效,所以看起来警告是错误的。如何消除警告?

  import scala.reflect.runtime.{universe => u}

  val docs = {
    val ann = u.typeOf[T].members
      .collect { case m: u.MethodSymbol if m.isGetter => m }
      .find(_.name.decoded == prop.propertyName)

    val docAnnotation = ann.flatMap(_.annotations.find(_.tpe.typeSymbol.name.decoded == "docs"))
    val trees = docAnnotation.map(_.scalaArgs).getOrElse(Nil)
    val args = trees.map {
      case u.Apply(_, List(u.Literal(u.Constant(value)))) => Some(value.asInstanceOf[String])
      case u.Select(_, name) if name.decoded == "None" => None
    }
    val safeGetArg = args.lift(_: Int).flatten

    Documentation(safeGetArg(0), safeGetArg(1))
  }

1 个答案:

答案 0 :(得分:3)

消除u,消除警告?

apm@mara:~$ scala210
Welcome to Scala version 2.10.4 (OpenJDK 64-Bit Server VM, Java 1.7.0_25).
Type in expressions to have them evaluated.
Type :help for more information.

scala> import scala.reflect.runtime.universe
import scala.reflect.runtime.universe

scala> import universe._
import universe._

scala> class X { val x = 7 ; var y = "hi" }
defined class X

scala> typeOf[X].members collect { case m: MethodSymbol => m }
res0: Iterable[reflect.runtime.universe.MethodSymbol] = List(method y_=, method y, value x, constructor X, method $asInstanceOf, method $isInstanceOf, method synchronized, method ##, method !=, method ==, method ne, method eq, method notifyAll, method notify, method clone, method getClass, method hashCode, method toString, method equals, method wait, method wait, method wait, method finalize, method asInstanceOf, method isInstanceOf, method !=, method ==)

scala> typeOf[X].members collect { case m: MethodSymbol if m.isGetter => m }
res1: Iterable[reflect.runtime.universe.MethodSymbol] = List(method y, value x)