What is the difference in Kotlin between var and val?
Learning Kotlin I came across the following doubt, according to the documentation:
Classes in Kotlin can have properties. These can be declared as mutable, using the var keyword or read-only using the val keyword.
classes in Kotlin can have properties. These can be declared as mutable, using the keyword var
or read-only using the Keyword val
.
I understood the difference between the types of variable declaration, but how to explain the code below in which money
and myMoney
are declared as val
and one of them allows you to change its value and the other does not?
fun main(args: Array<String>) {
data class Money(var value: Int)
operator fun Money.plusAssign(value: Money) {
this.value += value.value
}
val money = Money(10)
money += Money(20)
val myMoney = 10
myMoney += 20 //erro
println(money.value)
}
From what I understood from the code Money
is a class, I still wanted to understand the use of val
in this statement.
1 answers
val
declares an immutable variable and var
declares a changeable variable, so the compiler detected that you tried to change the value of something you can't. Looks like you already know that. But there's a catch.
What you have in the variable money
is just a reference to an object Money
. Nothing prevents from changing the object itself. The immutability is only of the contents of the variable, not the object, and money += Money(20)
only changes the object, not its reference, i.e. does not create a new one object, a new identity.
Some people prefer to say that the variable is read-only and not immutable. I see no problem calling it immutable, as long as you understand the difference between the variable and the object. But you can say it's readonly
, C# calls it that. I disagree a bit because every variable that can only read is immutable, the fact that its referenced object is mutable does not change the situation of the variable itself.
Already myMoney
is a type by value, it has its own identity, it has no reference, it can only change its value in the variable itself, which is forbidden by the compiler.
Kotlin prefers immutability until he needs the opposite. The language encourages a different style of programming.