[ad_1]
Comparing val
to a final is wrong!
var
s are mutable val
s are read only; Yes val cannot be reassigned just like final variables from Java but they can return a different value over time, so saying that they are immutable is kind of wrong;
Consider the following
var a = 10
a = 11 //Works as expected
val b = 10
b = 11 //Cannot Reassign, as expected
So for so Good!
Now consider the following for val
s
val d
get() = System.currentTimeMillis()
println(d)
//Wait a millisecond
println(d) //Surprise!, the value of d will be different both times
Hence, vars can correspond to nonfinal variables from Java, but val aren’t exactly final variables either;
Although there are const
in kotlin which can be like final
, as they are compile time constants and don’t have a custom getter, but they only work on primitives
[ad_2]