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

后端 未结 2 1934
孤独总比滥情好
孤独总比滥情好 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:27

    You can't "pattern match" on a variable that is not a constant.
    Stream.empty is not a "stable" identifier since it represents some method:

    /** The empty stream */
      override def empty[A]: Stream[A] = Empty
    

    that could potentially return any value at any time.
    Compiler isn't aware that its returned value is always Empty, so it detects it as a potential changing variable.
    Too deep for it to detect it.

    However, when you assign the method's retult to a val (being a stable identifier since immutable), your code is able to process to pattern matching using it.

    You might read this, evoking an hypothesis explaining why pattern matching expects a stable identifier.

提交回复
热议问题