为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

狐的传说 2018-10-05 09:19:46
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.


查看完整回答
反对 回复 2018-10-21
  • 2 回答
  • 0 关注
  • 2577 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信