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

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

问题描述

Kotlin中的 var val 有什么区别?

What is the difference between var and val in Kotlin?

我已经通过以下链接:

KotlinLang:属性和字段

如该链接所述:

只读属性声明的完整语法与可以通过以下两种方式进行更改:以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

http://blog.danlew.net/2017/05/30/mutable-vals-in-kotlin/

这篇关于Kotlin中的var和val有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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