anlex N
03/03/2024, 3:12 PManlex N
03/04/2024, 3:19 AManlex N
03/04/2024, 7:33 AMdmitriy.novozhilov
03/04/2024, 7:37 AMdmitriy.novozhilov
03/04/2024, 7:45 AManlex N
03/04/2024, 8:55 AMdmitriy.novozhilov
03/04/2024, 9:03 AMKlitos Kyriacou
03/04/2024, 9:37 AMfun foo(list: MutableList<String>) {
list = arrayListOf<String>("bar")
}
If Kotlin was "pass by reference" in the same way as C++ and C#, then the above function foo
would change the passed parameter list
to a list containing an element "bar". But Kotlin is not pass-by-reference in this way. You can't change the value of a passed variable.
I think what Dmitriy meant was that variables (except primitives) hold a reference to an object. So even though you pass the value of a variable to a function, that value is the reference of the object.dmitriy.novozhilov
03/04/2024, 9:39 AManlex N
03/04/2024, 10:14 AManlex N
03/04/2024, 12:38 PMKlitos Kyriacou
03/04/2024, 12:52 PMclass Wrapper<T>(var value: T)
fun foo(x: Wrapper<Int>) {
x.value = 456
}
int main() {
val x = Wrapper(123)
foo(x)
check(x.value == 456)
}
This is not idiomatic Kotlin. In Kotlin, we prefer to keep things immutable, so we would probably in the above case just write a function that takes one value and returns another value, rather than mutating.anlex N
03/04/2024, 12:57 PManlex N
03/04/2024, 1:00 PManlex N
03/04/2024, 1:43 PMArjan van Wieringen
03/04/2024, 4:33 PManlex N
03/06/2024, 11:09 AM