val和无参数def之间的微妙差异 [英] Subtle differences between val and parameterless def
问题描述
val Extractor = new AnyRef {def unapply(s:String)=>一些(s)}
val x =hellomatch {case Extractor(s)=> s
将 val提取器
更改为 def Extractor
打破了代码。为什么这样?有点令人失望,因为我希望完整的透明性能够让我从vals(生成方法)变为defs,反之亦然。我不知道还有什么可以做一个但不是另一个?
我不知道我可以提供一个详尽的列表,但我可以在这种情况下解释发生了什么。
Extractor
必须是一个稳定的标识符。请参阅 Scala语言规范的第8.1.8节。 (A def
不稳定; val
是。)
稳定的标识符具有一些很好的属性,可以使它们更简单地计算并具有更多的优化可能性。
Ok, this is is not another question about fundamental differences between vals & defs or functions and methods. I see that while this compiles:
val Extractor = new AnyRef { def unapply(s :String) => Some(s) }
val x = "hello" match { case Extractor(s) => s }
changing val Extractor
to def Extractor
breaks the code. Why is it so? It's a bit disappointing, as I hoped for complete trasnparency that would let me change the implementation from vals (generating methods anyway) to defs, or vice versa. I wonder what else can be done with one but not another?
I'm not sure I can supply an exhaustive list, but I can explain what's going on in this case.
Extractor
has to be a stable identifier. See Section 8.1.8 of the Scala Language Specification. (A def
is not stable; a val
is.)
Stable identifiers have certain nice properties that allow them to be more simply computed and have greater optimization possibilities.
这篇关于val和无参数def之间的微妙差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!