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.
The difference between val and var is that val makes a variable immutable — like final in Java — and var makes a variable mutable. Because val fields can't vary, some people refer to them as values rather than variables.
In Kotlin, val is also used for declaring a variable. Both "val" and "const val" are used for declaring read-only properties of a class. The variables declared as const are initialized at the runtime. val deals with the immutable property of a class, that is, only read-only variables can be declared using val.
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.
Kotlin uses two different keywords to declare variables: val and var . Use val for a variable whose value never changes. You can't reassign a value to a variable that was declared using val .
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With