主构造函数的参数需加上 var 和 val 这只是属性声明及主构造函数初始化属性的一种简洁语法,是将该变量作为类的成员变量来使用,是因为主构造函数是类头的一部分,在其中声明属性使得属性的声明变得方便、简洁。
class VariableTest(val a1: Int, var a2: Int) {
constructor(a6: Int) : this(1, 2)
fun variableTest(a3: Int, a4: Int) {
println("$a1, $a2, $a3, $a4")
a3 = 5
}
}
复制代码
在该示例中可以看到,次构造函数是不带val或者var关键字的。同样的函数也是没有携带val或者var关键字的。
给a3赋值会包错,提示 Val cannot be reassigned,说明次构造函数和函数中的参数都是val类型的。
早期Kotlin版本中,函数的参数是可以使用var或者val来定义参数是可变的还是不可变的。后来规定函数参数是不可变的,即val。Kotlin M5.1变更日志
The main reason is that this was confusing: people tend to think that this means passing a parameter by reference, which we do not support (it is costly at runtime). Another source of confusion is primary constructors: “val” or “var” in a constructor declaration means something different from the same thing if a function declarations (namely, it creates a property). Also, we all know that mutating parameters is no good style, so writing “val” or “var” infront of a parameter in a function, catch block of for-loop is no longer allowed.