var vs val in kotlin code example
Example 1: what is difference between val and var kotlin
fun main() {
val number = 1
number = 2
}
fun main() {
var number = 1
number = number + 9
println(number)
}
Example 2: kotlin var val
+----------------+-----------------------------+---------------------------+
| | val | var |
+----------------+-----------------------------+---------------------------+
| Reference type | Immutable (once initialized | Mutable (can change value)|
| | can't be reassigned) | |
+----------------+-----------------------------+---------------------------+
| Example | val n = 20 | var n = 20 |
| | n++ | |
+----------------+-----------------------------+---------------------------+
Example 3: kotlin difference between val and var
fun main() {
var number = 1
}
fun main() {
var number = 1
number = number + 9
println(number)
}
Example 4: kotlin var and val
val declares a read-only property, var a mutable one