The initialization of variables in Scala is done using three keywords def, var, and val. The keywords var and val both are used to assign memory to variables at the running only. The difference is in the mutability of variables that are initialized using these keywords.
Scala中变量的初始化使用三个关键字def, var和val完成 。 关键字var和val都仅在运行时用于为变量分配内存。 区别在于使用这些关键字初始化的变量的可变性 。
var keyword initializes variables that are mutable, and the val keyword initializes variables that are immutable.
var关键字初始化可变的变量,而val关键字初始化不变的变量。
Scala中var和val关键字之间的差异 (Differences between var and val keywords in Scala)
var Keyword | val Keyword |
---|---|
Used to initialize variables in Scala. | Used to initialize read only variables in Scala. |
Variables are initialized at compile time. | Variables are initialized at compile time |
Variable defined are mutable variables. | Variables defined are immutable variables. |
Values are not constant for var variables. | Values are constant for val variables. |
Changing the value of the variable in the program does not cause an error. | Changing the value of the variable is an error in the case of var declaration. |
Example, Counter, loop variable, sum, etc. | Example, name, id, constants. |
|
var关键字 | val关键字 |
---|---|
用于初始化Scala中的变量。 | 用于初始化Scala中的只读变量。 |
变量在编译时初始化。 | 变量在编译时初始化 |
定义的变量是可变变量。 | 定义的变量是不可变的变量。 |
对于var变量,值不是恒定的。 | 值对于val变量是恒定的。 |
在程序中更改变量的值不会导致错误。 | 在var声明的情况下,更改变量的值是错误的。 |
例如,计数器,循环变量,总和等。 | 示例,名称,ID,常量。 |
|
Both declarations are valid in Scala and you can you both in the program together if needed. Both keywords support all data types initialization in both explicit and automatic way.
这两个声明在Scala中都是有效的,如果需要,您可以在程序中一起使用。 这两个关键字都支持显式和自动方式的所有数据类型初始化。
The concept of mutability is from java’s String that is immutable. But in Scala you can make any variable immutable this gives the user a way to restrict some variable usage to read-only.
可变性的概念来自于不可变的java的String。 但是在Scala中,您可以使任何变量不可变,这为用户提供了一种将某些变量的使用限制为只读的方式。
翻译自: https://www.includehelp.com/scala/difference-between-var-and-val-keywords-in-scala.aspx