kotlin 为什么构造函数的参数可以加上var val修饰,而普通函数就不行呢?
2 回答
Qyouu
TA贡献1786条经验 获得超11个赞
早期的 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.
- 2 回答
- 0 关注
- 2639 浏览
添加回答
举报
0/150
提交
取消