Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pattern matching 中 type erasure #22

Open
zhongl opened this issue Feb 23, 2014 · 0 comments
Open

Pattern matching 中 type erasure #22

zhongl opened this issue Feb 23, 2014 · 0 comments
Labels

Comments

@zhongl
Copy link
Member

zhongl commented Feb 23, 2014

问题

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
}

参考

@zhongl zhongl added 问题 and removed 问题 labels Feb 23, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant