为什么在 Scala 中使用 def 和 val,反之亦然 [英] why use def and val in Scala or vice versa
问题描述
我知道这之前已经在其他帖子中讨论过,并且我理解使用 def
和 val
之间的基本区别.def
用于定义方法,val
用于定义不可变引用.通过提出这个问题,我试图完成的是了解 def
是否还有其他内容.它可以与 val
互换使用吗?
I know this has been discussed on SO in other posts before and I understand the basic difference between the use of def
and val
. def
is used for defining a method and val
for an immutable reference. What I am trying to accomplish by asking this question is to understand if there is something more to def
. Can it be used interchangeably with a val
?
最近我尝试了以下代码,如果我目前对 def
的理解足够,我无法说服自己:
Recently I tried the following code and cannot convince myself if my present understanding of def
is sufficient:
scala> def i: Int = 3
i: Int
scala> i
res2: Int = 3
所以我很好奇,这等价于val i = 3
吗?
So I am curious, is this equivalent to val i = 3
?
然后我尝试了这个:
scala> i()
<console>:9: error: Int does not take parameters
i()
我这样做只是为了测试我对 def
语义的理解.现在我想知道,当 i
是一个方法时,为什么 Scala 会抱怨...不带参数"?
I did this just to test my understanding of the semantics of def
. Now I want to know, when i
is a method, why Scala complains with "...does not take parameters"?
接下来我尝试了以下操作:
Next I tried the following:
scala> def i(): Int = 3
i: ()Int
scala> i()
res4: Int = 3
这一次 Scala 似乎同意 i
是一种方法.那么我可以使用 def
代替 val
来声明和初始化变量吗?
This time Scala seems to agree that i
is a method. So can I use def
in place of val
interchangeable to declare and initialize a variable?
推荐答案
Both
def i = 3
和
def i() = 3
声明方法.唯一的区别是,第一个是没有参数列表的方法,第二个是带有空参数列表的方法.前者通常用于没有副作用的方法,后者用于有副作用的方法.如果值永远不会改变并且您想避免重新计算它,您应该使用 val 而不是 def.def 每次被调用时都会重新计算,而 val 只被赋值一次.
declare methods. The only difference is, that the first one is a method without a parameter list and the second is a method with an empty parameter list. The former is usually used for methods without side effects and the latter for methods with side effects. You should use a val instead of a def if the value never changes and you want to avoid recomputing it. A def gets recomputed every time it is called, while a val is assigned a value only once.
这篇关于为什么在 Scala 中使用 def 和 val,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!