问题描述
Kotlin 中 var
和 val
有什么区别?
What is the difference between var
and val
in Kotlin?
我已经浏览过这个链接:
I have gone through this link:
如本链接所述:
只读属性声明的完整语法不同于可变的有两种方式:它以 val 而不是 var 开头,并且不允许使用 setter.
但就在之前有一个使用 setter 的例子.
But just before there is an example which uses a setter.
fun copyAddress(address: Address): Address {
val result = Address() // there's no 'new' keyword in Kotlin
result.name = address.name // accessors are called
result.street = address.street
// ...
return result
}
var
和 val
之间的确切区别是什么?
What is the exact difference between var
and val
?
为什么我们需要两者?
这不是 因为我问的是与文档中特定示例相关的疑问,而不仅仅是一般性的疑问.
This is not a duplicate of Variables in Kotlin, differences with Java: 'var' vs. 'val'? as I am asking about the doubt related to the particular example in the documentation and not just in general.
推荐答案
val
和 var
都用于声明变量.
val
and var
both are used to declare a variable.
var 就像 general 变量,它在 kotlin 中被称为可变变量,可以多次赋值.
val 就像 Final 变量,它在 kotlin 中被称为不可变的,并且只能初始化一次.
val is like Final variable and it's known as immutable in kotlin and can be initialized only single time.
有关val
和var
的更多信息,请参阅以下链接
For more information what is val
and var
please see below link
http://blog.danlew.net/2017/05/30/mutable-vals-in-kotlin/
这篇关于Kotlin 中 var 和 val 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!