Kotlin 中的 var 和 val 有什么区别? [英] What is the difference between var and val in Kotlin?

查看:32
本文介绍了Kotlin 中的 var 和 val 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Kotlin 中 varval 有什么区别?

What is the difference between var and val in Kotlin?

我已经浏览过这个链接:

I have gone through this link:

KotlinLang:属性和字段

如本链接所述:

只读属性声明的完整语法不同于可变的有两种方式:它以 val 而不是 var 开头,并且不允许使用 setter.

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.

但就在之前有一个使用 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
}

varval 之间的确切区别是什么?

What is the exact difference between var and val?

为什么我们需要两者?

这不是Kotlin 中的变量,与 Java 的区别:'var' vs. '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.

推荐答案

valvar 都用于声明变量.

val and var both are used to declare a variable.

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.

有关valvar 的更多信息,请参阅以下链接

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 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆