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:
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.
Thanks in advance!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With