kotlinvariables

What is the difference between var and val in Kotlin?


What is the difference between var and val in Kotlin?

I have gone through this link:

KotlinLang: Properties and Fields

As stated on this link:

The full syntax of a read-only property declaration differs from a mutable one in two ways: it starts with val instead of var and does not allow a setter.

But just before there is an example which uses a setter.

fun copyAddress(address: Address): Address {
    val result = Address() // there's no 'new' keyword in Kotlin
    result.name = address.name // accessors are called
    result.street = address.street
    // ...
    return result
}

What is the exact difference between var and val?

Why do we need both?

This is not a duplicate of Variables in Kotlin, differences with Java: 'var' vs. 'val'? as I am asking about the doubt related to the particular example in the documentation and not just in general.


Solution

  • In your code result is not changing, its var properties are changing. Refer comments below:

    fun copyAddress(address: Address): Address {
        val result = Address() // result is read only
        result.name = address.name // but not their properties.
        result.street = address.street
        // ...
        return result
    }
    

    val is same as the final modifier in java. As you should probably know that we can not assign to a final variable again but can change its properties.