Scala中的var和val定义有什么区别?为什么这两种定义都需要?为什么你会选择val而不是var,反之亦然?


当前回答

简单来说:

var = 变量

Val =变量+ final

其他回答

在javascript方面,它与

val -> const 是 -> 是

Val是最终值,即不能设置。在java中考虑final。

简单来说:

var = 变量

Val =变量+ final

从c++的角度思考,

val x: T

是否类似于指向非常量数据的常量指针

T* const x;

var x: T 

类似于指向非常量数据的非常量指针吗

T* x;

偏好val而不是var增加了代码库的不可变性,这有助于它的正确性、并发性和可理解性。

要理解常量指针指向非常量数据的含义,请考虑以下Scala代码片段:

val m = scala.collection.mutable.Map(1 -> "picard")
m // res0: scala.collection.mutable.Map[Int,String] = HashMap(1 -> picard)

这里的“指针”val m是常量,所以我们不能将它重新赋值为指向其他东西

m = n // error: reassignment to val

但是我们确实可以改变m指向的非常数数据本身

m.put(2, "worf")
m // res1: scala.collection.mutable.Map[Int,String] = HashMap(1 -> picard, 2 -> worf)

val表示不可变,var表示可变

解释一下,“val表示值,var表示变量”。

A distinction that happens to be extremely important in computing (because those two concepts define the very essence of what programming is all about), and that OO has managed to blur almost completely, because in OO, the only axiom is that "everything is an object". And that as a consequence, lots of programmers these days tend not to understand/appreciate/recognize, because they have been brainwashed into "thinking the OO way" exclusively. Often leading to variable/mutable objects being used like everywhere, when value/immutable objects might/would often have been better.