3

有人可以解释为什么这会发出擦除警告吗?

def optionStreamHead(x: Any) =
  x match {
    case head #:: _ => Some(head)
    case _ => None
  }

给出:

warning: non variable type-argument A in type pattern scala.collection.immutable.Stream[A] is unchecked since it is eliminated by erasure
            case head #:: _ => Some(head)

我意识到我可以写这个案例if (x.isInstanceOf[Stream[_]]) ...而不会收到警告,但在我的案例中,我实际上想使用模式匹配并且有一大堆我不明白的警告似乎很糟糕

这是一个同样令人费解的案例:

type IsStream = Stream[_]

("test": Any) match {
  case _: Stream[_] => 1 // no warning
  case _: IsStream => 2 // type erasure warning
  case _ => 3
}
4

1 回答 1

3

两者都是 2.9 中的错误,已在 2.10 中解决。在 2.10 中,我们获得了一个新的模式匹配引擎(称为 virtpatmat 用于虚拟模式匹配器):

scala> def optionStreamHead(x: Any) =
  x match {
    case head #:: _ => Some(head)
    case _ => None
  }
optionStreamHead: (x: Any)Option[Any]

scala> optionStreamHead(0 #:: Stream.empty)
res14: Option[Any] = Some(0)

scala> ("test": Any) match {
     |   case _: Stream[_] => 1 // no warning
     |   case _: IsStream => 2 // type erasure warning
     |   case _ => 3
     | }
<console>:11: warning: unreachable code
                case _: IsStream => 2 // type erasure warning
                                    ^
res0: Int = 3
于 2012-10-06T22:41:45.863 回答