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 關注
- 2673 瀏覽
添加回答
舉報
0/150
提交
取消