对恒定值使用def和val有什么影响 [英] What are the implications of using def vs. val for constant values

查看:163
本文介绍了对恒定值使用def和val有什么影响的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Scala中使用 def val 来定义一个常量,不可变的值有什么影响?我明显可以写出如下内容:

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

这两种说法有什么区别?哪一个表现更好/是推荐方式还是更习惯?

解决方案

假设这些是类级声明:



编译器会产生一个 val final ,这可以导致更好的优化代码VM



def 不会将值存储在对象实例中,因此会节省内存,但要求每次评估该方法。



为了两全其美,创建伴随对象并声明常量为 val s there。



即而不是

  class Foo {
val MyConstant = 42
}


$ b $ p $ class Foo { }

object Foo {
val MyConstant = 42
}


What are the implications of using def vs. val in Scala to define a constant, immutable value? 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.

A def won't store the value in the object instance, so will save memory, but requires the method to be evaluated each time.

For the best of both worlds, make a companion object and declare constants as vals there.

i.e. instead of

class Foo {
  val MyConstant = 42
}

this:

class Foo {}

object Foo {
  val MyConstant = 42
}

这篇关于对恒定值使用def和val有什么影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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