Scala中的var和val定义有什么区别?为什么这两种定义都需要?为什么你会选择val而不是var,反之亦然?
当前回答
Val表示不可变,var表示可变
您可以将val视为Java编程语言的final key world或c++语言的const key world。
其他回答
Val表示不可变,var表示可变。
完整的讨论。
Val是最终值,即不能设置。在java中考虑final。
区别在于var可以被重新赋值,而val则不能。可变性,或其他任何实际分配的东西,是一个次要问题:
import collection.immutable
import collection.mutable
var m = immutable.Set("London", "Paris")
m = immutable.Set("New York") //Reassignment - I have change the "value" at m.
而:
val n = immutable.Set("London", "Paris")
n = immutable.Set("New York") //Will not compile as n is a val.
因此:
val n = mutable.Set("London", "Paris")
n = mutable.Set("New York") //Will not compile, even though the type of n is mutable.
如果您正在构建一个数据结构,并且它的所有字段都是val,那么该数据结构因此是不可变的,因为它的状态不能改变。
Val表示最终值,不能重新赋值
而Var可以在以后重新分配。
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.