kotlin 为什么构造函数的参数可以加上var val修饰,而普通函数就不行呢?

kotlin 为什么构造函数的参数可以加上var val修饰,而普通函数就不行呢?

狐的传说
浏览 2585回答 2
2回答

Qyouu

早期的 Kotlin 版本函数参数是可以定义成 var 的,不过后来官方明确了「函数参数都是不可变」这一点。在这篇更新日志里可以找到说明:The main reason is that this was confusing: people tend to think thatthis means passing a parameter by reference, which we do not support(it is costly at runtime). Another source of confusion is primaryconstructors: “val” or “var” in a constructor declaration meanssomething different from the same thing if a function declarations(namely, it creates a property). Also, we all know that mutatingparameters is no good style, so writing “val” or “var” in front of aparameter in a function, catch block of for-loop is no longer allowed.
打开App,查看更多内容
随时随地看视频慕课网APP