gpt4 book ai didi

kotlin - Kotlin中的var和val有什么区别?

转载 作者:IT老高 更新时间:2023-10-28 13:25:53 25 4
gpt4 key购买 nike

Kotlin中的varval有什么区别?
我已经通过这个链接:
KotlinLang: Properties and Fields
如该链接所述:

The full syntax of a read-only property declaration differs from amutable one in two ways: it starts with val instead of var and doesnot allow 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
}
varval之间的确切区别是什么?
为什么我们都需要?
这是 ,而不是Variables in Kotlin, differences with Java: 'var' vs. 'val'?重复,因为我是在询问与文档中特定示例相关的疑问,而不仅仅是一般情况。

最佳答案

在您的代码中result不变,其var属性也在变化。请参阅以下评论:

fun copyAddress(address: Address): Address {
val result = Address() // result is read only
result.name = address.name // but not their properties.
result.street = address.street
// ...
return result
}
val与Java中的 final修饰符相同。您可能已经知道,我们不能再次分配给 final变量,但可以更改其属性。

关于kotlin - Kotlin中的var和val有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44200075/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com