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

查看:86
本文介绍了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 中的参数不能重新分配,因为它们的作用类似于 vals:

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.

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

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