What’s the difference in Kotlin between var and val?

Asked

Viewed 4,428 times

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?

Código

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.

1 answer

12


val declares a variable immutable and var declares a variable changeable, so the compiler detected that you tried to change the value of something you can’t. It seems that you already know this. But there’s one catch.

What is in the variable money is only a reference to an object Money. Nothing prevents you from changing the object itself. Immutability is only of the variable content, not of the object and money += Money(20) only changes the object, not its reference, that is, it does not create a new object, a new identity.

Some people prefer to say that the variable is read-only and not immutable. I see no problem in calling it immutable as long as I understand the difference between the variable and the object. But you can say it’s readonly, C# calls it that. I disagree a little 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, has its own identity, has no reference, can only change its value in the variable itself, which is prohibited by the compiler.

Kotlin prefers immutability until he needs otherwise. The language encourages a different style of programming.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.