val和无参数def之间的微妙差异 [英] Subtle differences between val and parameterless def

查看:102
本文介绍了val和无参数def之间的微妙差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,这不是关于vals&定义或功能和方法。我看到,虽然这编译:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆