Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala's Stream erasure warning

Could someone explain why this gives an erasure warning?

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

Gives:

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)

I realize I can write this case if (x.isInstanceOf[Stream[_]]) ... and not get the warning, but in my case I actually want to use pattern matching and having a whole bunch of warnings I don't understand seems bad

And here's an equally puzzling case:

type IsStream = Stream[_]

("test": Any) match {
  case _: Stream[_] => 1 // no warning
  case _: IsStream => 2 // type erasure warning
  case _ => 3
}
like image 995
Heptic Avatar asked Jan 25 '26 21:01

Heptic


1 Answers

Both are bugs in 2.9 that are solved in 2.10. In 2.10 we get a new pattern matching engine (called virtpatmat for virtual pattern matcher):

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
like image 105
kiritsuku Avatar answered Jan 27 '26 11:01

kiritsuku



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!