kotlin 主构造函数的参数可以加上var val,普通函数却不能用var或者val

初学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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值