科特林的瓦尔和瓦尔 [英] Val and Var in Kotlin
问题描述
在Kotlin中var
和val
有什么区别?
What is the difference between var
and val
in Kotlin?
我已经通过以下链接:
https://kotlinlang.org/docs/reference/properties.html
如该链接所述:
只读属性声明的完整语法与 可以通过以下两种方式进行更改:以val而不是var开头并执行 不允许二传手.
The full syntax of a read-only property declaration differs from a mutable one in two ways: it starts with val instead of var and does not allow a 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
都用于声明变量.
var 类似于 general 变量,在 kotlin 中被称为可变变量,可以多次分配.
var is like general variable and it's known as a mutable variable in kotlin and can be assigned multiple times.
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
这篇关于科特林的瓦尔和瓦尔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!