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.
Question&Answers:os