Kotlin 是“按值传递"吗?还是“传递引用"?
据我所知,Java 是来自这篇文章的值传递.我来自 Java 背景,我想知道 Kotlin 使用什么在两者之间传递值.就像在 扩展 或 方法 等
As I know Java is pass-by-value from this post. I am from Java background I wonder what Kotlin is using for passing values in between. Like in Extensions or Methods etc.
它使用与 Java 相同的原理.总是传值,你可以想象传了一个副本.对于原始类型,例如Int
这个很明显,这样一个参数的值会被传递到一个函数中,并且不会修改外部变量.请注意,Kotlin 中的参数不能重新分配,因为它们的作用类似于 val
s:
It uses the same principles like Java. It is always pass-by-value, you can imagine that a copy is passed. For primitive types, e.g. Int
this is obvious, the value of such an argument will be passed into a function and the outer variable will not be modified. Please note that parameters in Kotlin cannot be reassigned since they act like val
s:
fun takeInt(a: Int) {
a = 5
}
此代码将无法编译,因为 a
无法重新分配.
This code will not compile because a
cannot be reassigned.
对于对象来说有点困难,但它也是按值调用.如果你用一个对象调用一个函数,它的引用副本会被传递给那个函数:
For objects it's a bit more difficult but it's also call-by-value. If you call a function with an object, a copy of its reference is passed into that function:
data class SomeObj(var x: Int = 0)
fun takeObject(o: SomeObj) {
o.x = 1
}
fun main(args: Array<String>) {
val obj = SomeObj()
takeObject(obj)
println("obj after call: $obj") // SomeObj(x=1)
}
您可以使用传递给函数的引用来更改实际对象.
You can use a reference passed into a function to change the actual object.