简体   繁体   English

将def与val用于常量值有什么含义

[英]What are the implications of using def vs. val for constant values

What are the implications of using def vs. val in Scala to define a constant, immutable value? 在Scala中使用defval来定义一个常量的不可变值有什么含义? I obviously can write the following: 我显然可以写下面的内容:

val x = 3;
def y = 4;
var a = x + y; // 7

What's the difference between those two statements? 这两个陈述之间有什么区别? Which one performs better / is the recommended way / more idiomatic? 哪一个表现更好/是推荐的方式/更惯用? When would I use one over the other? 我何时会使用一个而不是另一个?

Assuming these are class-level declarations: 假设这些是类级声明:

The compiler will make a val final , which can lead to better-optimised code by the VM. 编译器将进行val final ,这可以导致VM更好地优化代码。

A def won't store the value in the object instance, so will save memory, but requires the method to be evaluated each time. def不会将值存储在对象实例中,因此会节省内存,但每次都需要对方法进行评估。

For the best of both worlds, make a companion object and declare constants as val s there. 为了两全其美,建立一个伴侣对象并在那里声明常量为val

ie instead of 即代替

class Foo {
  val MyConstant = 42
}

this: 这个:

class Foo {}

object Foo {
  val MyConstant = 42
}

The val is evaluated once and stored in a field. val被评估一次并存储在字段中。 The def is implemented as a method and is reevaluated each time, but does not use memory space to store the resulting value. def作为一种方法实现,并且每次都重新评估,但不使用内存空间来存储结果值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM