Scala的Stream擦除警告

时间:2012-10-06 22:01:44

标签: scala pattern-matching type-erasure

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

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
}

1 个答案:

答案 0 :(得分: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