Among all the many keywords that Kotlin comes with, there exists val
and var
. What are they used for? What are the differences, and why would you use one over another?
They are both used to declare variables in Kotlin. But how are they different?
What is val
?
val
is used to declare a variable that is read-only, and who’s value does not change.
Note that this only applies to the parent variable, and not it’s properties. The properties of the variable are still mutable.
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
}
What is var
?
Just like val
, var
is also used to declare a variable. However, its value can be mutable.
var
is used to declare a variable that can be changed. It can also be assigned multiple times.
fun getName(address: Address): String {
var result = "Name: " // result is mutable (can be changed)
// ...
return result + address.name
}