【问题标题】:Scala's Stream erasure warningScala 的 Stream 擦除警告
【发布时间】:2012-10-07 16:14:50
【问题描述】:

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

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
}

【问题讨论】:

    标签: scala pattern-matching type-erasure


    【解决方案1】:

    两者都是 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
    

    【讨论】:

    • 第二个例子呢,这也是scala的bug吗?
    • @Heptic:抱歉,我一定忽略了这一点。我编辑了我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 2012-05-28
    • 2020-07-27
    • 2012-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多