What is the difference in Kotlin between var and val?

10

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.

    
asked by anonymous 27.07.2017 / 17:40

1 answer

10

val declares a variable immutable and var declares a #

What you have in the money variable is just a reference to a Money object. Nothing prevents you from changing the object itself. The immutability is only of the contents of the variable, 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 do not see problem calling immutable as long as you understand the difference between the variable and the object. But you can say it's readonly , C # calls it like this. I disagree a bit because any variable that can only read is immutable, the fact that its referenced object is changeable does not change the situation of the variable itself.

Since 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. Language encourages a different style of programming.

    
27.07.2017 / 17:57