Scala中var和val关键字之间的区别

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, varval完成 。 关键字varval都仅在运行时用于为变量分配内存。 区别在于使用这些关键字初始化的变量的可变性

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 Keywordval 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.
Syntax: var myVar = 32; 
var关键字 val关键字
用于初始化Scala中的变量。 用于初始化Scala中的只读变量。
变量在编译时初始化。 变量在编译时初始化
定义的变量是可变变量。 定义的变量是不可变的变量。
对于var变量,值不是恒定的。 值对于val变量是恒定的。
在程序中更改变量的值不会导致错误。 在var声明的情况下,更改变量的值是错误的。
例如,计数器,循环变量,总和等。 示例,名称,ID,常量。
Syntax: var myVar = 32; 

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值