初学kotlin的时候有个疑问一直没有搞懂,为啥kotlin构造函数里面的参数可以用var或者val,普通的fun却不可以,这到底是为什么呢?
我们知道kotlin 声明变量的时候用的语法是
val name : String
主构造函数的参数加上 var 和 val 这只是声明属性以及从主构造函数初始化属性的一种简洁的语法,意思是将该变量作为类的成员变量来使用,是因为主构造函数是类头的一部分吧,在这里直接声明属性使得属性的声明变得很方便、简洁。
class People(val name: String) {}
相当于Java中
public class People{
public String name;
public People(String name) {
this.name = name;
}
}
而kotlin函数,就没有这种用法了,
早期的 Kotlin 版本函数参数是可以定义成 var 的,不过后来官方明确了「函数参数都是不可变」这一点。在这篇更新日志里可以找到说明:
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” in front of a
parameter in a function, catch block of for-loop is no longer allowed.
参考一些回答:
https://segmentfault.com/q/1010000011637287
https://www.imooc.com/wenda/detail/434996