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. This will influence the argument you passed in. But the reference itself, i.e. the value of the variable, will never be changed via a function call.