Kotlin值与作业参考 [英] Kotlin value vs. reference in assignment

查看:81
本文介绍了Kotlin值与作业参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个类引用另一个.不创建它的副本,但实际引用一个已经存在的实例.

I would need to have one class reference another. Not create a copy of it but have an actual reference to an already existing instance.

我也许可以用一个例子更好地解释它.我们有一个类Image:

I might be able to explain it better with an example. Were we have a class Image:

class Image(imgPath: String) {
    val height   : Int
    val width    : Int
    val rgbMatrix: MutableList< MutableList< Triple<Int, Int, Int> > >

    /* ... etc. ... */
}

现在说我想要一个类ImageManager,该类仅具有对已经存在的Image的引用:

Now say I want a class ImageManager that only has a reference to an already existing Image:

class ImageManager(val img: Image) {
   /* ... */
}

所以我可以有这种行为:

So I can have this behaviour:

val image = Image("/res/images/image.png")

val imageManager = ImageManager(image)

// Setting the pixel at (125, 25) to black
imageManager.img.rgbMatrix[125, 25] = Triple(0, 0, 0)

// Should print the update value(0, 0, 0)
print( image.rgbMatrix[125, 25] )

我的问题是:

  1. 在Kotlin中,何时分配任务分配参考,何时分配副本?

  1. In Kotlin when does in assignment assign a reference and when does it assign a copy?

我如何确定什么时候进行分配?

How can I determine what kind of assignment happens when?

官方文档中是否有详细说明的部分?如果找不到我.

Is there a part in the official docs where this is detailed? If there is I couldn't find it.

提前谢谢!

推荐答案

Similar to Java, Kotlin never implicitly copies objects on assignment. Variables always hold references to objects, and assigning an expression to a variable only copies a reference to the object, not the object itself.

在内部,每个值可以是原始值(IntBooleanChar等)或引用.赋值时,结果要么是原语的副本,要么是对同一对象的引用的副本,这永远不会导致被引用的对象被复制.

Under the hood, each value is either a primitive (Int, Boolean, Char etc.) or a reference. When a value is assigned, the result is either a copy of the primitive, or a copy of the reference to the same object, which never leads to the referenced object being copied.

据我所知,这种行为没有明确记录;而是假定它与Java中的相同.

As far as I can tell, this behavior is not explicitly documented; instead, it is assumed to be the same to that in Java.

另请参阅:是Kotlin按值传递"或通过引用传递"?

See also: Is Kotlin "pass-by-value" or "pass-by-reference"?

这篇关于Kotlin值与作业参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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