Kotlin - 变量 val 和 var

本文介绍了Kotlin编程语言中的变量声明,重点对比了只读变量`val`和可变变量`var`的使用。`val`用于声明不可变变量,一旦初始化后不能改变;而`var`用于声明可变变量,可以多次更改其值。文章强调了使用不可变变量有助于提高代码可读性,并提供了实例演示如何声明和使用这两种类型的变量。
摘要由CSDN通过智能技术生成

什么是变量

变量是一个值的存储空间,这个值可以是一个字符串、一个数字或者其他东西。 每个变量都有一个名称(或标识符)来区别于其他变量。 可以通过变量的名称访问值。变量是程序中最常用的元素之一。

声明变量

在开始使用变量之前,必须先声明它。要声明变量,Kotlin 提供两个关键字:

val

val (value 的简写)声明一个只读(注)变量(只是一个命名值或常量),在初始化后不能改变它(这并不完全正确,我们将在后面更详细地讨论),对应 Java 中的 final 变量。

注:关于只读还是不可变,Kotlin 文档使用了 read-only ,而 JetBrains Academy 上使用了 immutable 。

Lucifer Watson

Not exactly.
Read only or constant means that the variable cannot be reassigned whereas immutable means that value cannot be changed.
The following will fail because the variable is constant or read only.
val a = “hello”
a = a + " world"
The following will work but (if we ignore any compiler optimisation) there will now be three strings in memory, “hello”, " world", and “hello world” because strings are immutable, they cannot be changed once created. Here I am assuming that Kotlin is like most other languages in that regard.
var a = “hello”
a = a + " world"

https://kotlinlang.org/docs/referen

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值