10
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 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 to change its value and the other 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 understand of the code Money
is a class, yet I wanted to understand the use of val
in that statement.