Kotlin是“按价值传递"吗?或“通过引用传递"? [英] Is Kotlin "pass-by-value" or "pass-by-reference"?

查看:605
本文介绍了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 vals:

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.

这篇关于Kotlin是“按价值传递"吗?或“通过引用传递"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆