简体   繁体   English

函数参数的行为类似于Kotlin中的val类型的变量吗?

[英]Does function parameter behaves like a val type of variable in Kotlin?

I was creating a function and I tried to increase the value of the parameter which was declared as Integer. 我正在创建一个函数,并尝试增加声明为Integer的参数的值。 But it said that the value of that parameter can not be reassigned. 但是它说不能重新分配该参数的值。 I am a beginner so if I am missing some concept please tell me. 我是一个初学者,所以如果我缺少一些概念,请告诉我。

Yes, in Kotlin function parameters can't be changed. 是的,在Kotlin函数中无法更改参数。

(However, if they refer to mutable objects, then those objects can change. For example, if you declared fun a(b: List<String>) , then you could add another String to the List; but you couldn't set b to refer to a different List.) (但是,如果它们引用可变对象,则这些对象可以更改。例如,如果您声明fun a(b: List<String>) ,则可以向列表中添加另一个String;但是不能设置b以引用其他列表。)

This is different from Java, where parameters are variable (unless specified as final ). 这不同于Java,在Java中参数是可变的(除非指定为final )。

This behaviour was announced in Kotlin milestone M5.1, where it was explained as avoiding confusion (especially in constructors), and promoting good style. 这种行为是在Kotlin里程碑M5.1中宣布的 ,该行为被解释为避免混淆(尤其是在构造函数中),并促进了良好的风格。

See also this answer. 另请参阅答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM