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

后端 未结 2 1932
孤独总比滥情好
孤独总比滥情好 2021-01-07 16:41

The code below doesn\'t compile if I uncomment the line indicated. The compiler complains: \"stable identifier required\".

val Empty = Stream.empty    
val a         


        
2条回答
  •  伪装坚强ぢ
    2021-01-07 17:36

    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)
           }
    

提交回复
热议问题