The code below doesn't compile if I uncomment the line indicated. The compiler complains: "stable identifier required".
val Empty = Stream.empty val a = Stream.range(0, 5) a match { // case Stream.empty => println("nope") <-- does not work case Empty => println("compiles") <-- works case _ => println("ok") }
If I assign Stream.empty
to value Empty
first, it works, but it feels strange that you can't pattern match on such a fundamental value without such a hack.
Am I missing something?
Notes. Scala's pattern matching statement is most useful for matching on algebraic types expressed via case classes. Scala also allows the definition of patterns independently of case classes, using unapply methods in extractor objects.
Pattern matching is a way of checking the given sequence of tokens for the presence of the specific pattern. It is the most widely used feature in Scala. It is a technique for checking a value against a pattern. It is similar to the switch statement of Java and C.
You can't pattern match on Stream.empty
because it is a method (in object Stream
) that always returns the empty stream (but the compiler doesn't know that).
Instead of assigning val empty = Stream.empty
, you can match on Stream.Empty
, which is an Object
:
scala> a match { case Stream.Empty => println("done") case h #:: tl => println(h) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With