为什么我不能在 Scala 中对 Stream.empty 进行模式匹配? [英] 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")
}
如果我首先将 Stream.empty
赋值给 Empty
值,它可以工作,但是感觉很奇怪,如果没有这样的基本值,您无法对这样的基本值进行模式匹配黑客.
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.
我错过了什么吗?
推荐答案
您不能对 Stream.empty
进行模式匹配,因为它是一个 方法(在对象 Stream
) 总是返回空流(但编译器不知道).
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).
不是分配 val empty = Stream.empty
,你可以匹配 Stream.Empty
,它是一个 Object
:
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)
}
这篇关于为什么我不能在 Scala 中对 Stream.empty 进行模式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!