科特林的瓦尔和瓦尔 [英] Val and Var in Kotlin

查看:72
本文介绍了科特林的瓦尔和瓦尔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Kotlin中varval有什么区别?

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
}

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

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.

推荐答案

valvar都用于声明变量.

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/

这篇关于科特林的瓦尔和瓦尔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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