Pass by value or by reference in Kotlin: why can't I change a number in a function?
Hello everyone! I just started learning Kotlin after Java and got confused about the mechanism of passing arguments to functions. I read several articles but still don't fully understand.
Here's a simple example. I'm writing a function that should increase the passed number by 10:
```kotlin
fun increaseValue(x: Int) {
x = x + 10 // Compilation error: Val cannot be reassigned
}
```
The compiler complains that x is a val. I understand that parameters in Kotlin are immutable references (val). But then how does passing work for mutable objects? Here's another example:
```kotlin
data class Person(var name: String)
fun changeName(person: Person) {
person.name = "New Name" // This works
}
fun main() {
val p = Person("Old")
changeName(p)
println(p.name) // Prints "New Name"
}
```
Here
No answers yet.
Log in to leave an answer