CSUG / csug

China Scala User Group
261 stars 64 forks source link

Pattern matching 中 type erasure #22

Open zhongl opened 10 years ago

zhongl commented 10 years ago

问题

scala> val x : List[Any] = List(1.0,2.0,3.0)
x: List[Any] = List(1.0, 2.0, 3.0)

scala> x match {
     |   case l : List[Boolean] => l(0)
     |   case x                 => x
     | }
<console>:10: warning: non-variable type argument Boolean in type pattern List[Boolean] is unchecked since it is eliminated by erasure
                case l : List[Boolean] => l(0)
                         ^
res0: Any = 1.0

解决

import scala.reflect.runtime.universe._

class Def[C: TypeTag] {
  def unapply[X: TypeTag](c: X): Option[C] = {
    if (typeOf[X] <:< typeOf[C]) Some(c.asInstanceOf[C]) else None
  }
}

val BooleanList = new Def[List[Boolean]]

x match {
  case BooleanList(l) => l
  case x              => x
}

参考