What is the difference between var and val in Kotlin?
Solution 1:
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.
Solution 2:
val
and var
both are used to declare a variable.
var is like general variable and it's known as a mutable variable in kotlin and can be assigned multiple times.
val is like Final variable and it's known as immutable in kotlin and can be initialized only single time.
For more information what is val
and var
please see below link
http://blog.danlew.net/2017/05/30/mutable-vals-in-kotlin/
Solution 3:
variables defined with var are mutable(Read and Write)
variables defined with val are immutable(Read only)
Kotlin can remove findViewById and reduce code for setOnClickListener in android studio. For full reference: Kotlin awesome features
value of mutable variables can be changed at anytime, while you can not change value of immutable variables.
where should I use var and where val ?
use var where value is changing frequently. For example while getting location of android device
var integerVariable : Int? = null
use val where there is no change in value in whole class. For example you want set textview or button's text programmatically.
val stringVariables : String = "Button's Constant or final Text"