Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I pattern match on Stream.empty in Scala?

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?

like image 588
BasilTomato Avatar asked Feb 15 '15 20:02

BasilTomato


People also ask

Does Scala have pattern matching?

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.

How does Scala pattern matching work?

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.


1 Answers

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)        } 
like image 193
Marth Avatar answered Sep 22 '22 03:09

Marth