Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin value vs. reference in assignment [duplicate]

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.

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. ... */
}

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] )

My questions are:

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

  2. How can I determine what kind of assignment happens when?

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

Thanks in advance!

like image 660
Rares Dima Avatar asked Apr 02 '26 09:04

Rares Dima


1 Answers

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.

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.

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

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

like image 145
hotkey Avatar answered Apr 08 '26 15:04

hotkey