Learning Kotlin I came across the following question, 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 changeable by using the var
or read-only keyword using the val
keyword.
I understand the difference between the variable declaration types, but how to explain the code below where money
and myMoney
are declared as val
and one of them allows you to change its value and the other one does not? p>
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)
}
As I understand the code Money
is a class, I still wanted to understand the use of val
in this declaration.