什么是变量
变量是一个值的存储空间,这个值可以是一个字符串、一个数字或者其他东西。 每个变量都有一个名称(或标识符)来区别于其他变量。 可以通过变量的名称访问值。变量是程序中最常用的元素之一。
声明变量
在开始使用变量之前,必须先声明它。要声明变量,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"