Monday 2 April 2018

In kotlin difference between var and val

In Kotlin difference between VAR and VAL


VAR : Var is mutable variable in Kotlin i.e var is read and write value. We can change value many times or assigned value in class.

Example:


var x = 25
//first inialised the value of x
print(x)

 x= 26
//change the value x in many times in class 
print(x)


   

VAL : Val is immutable in Kotlin i.e val is read only. Val is like final value in java. We can use val where I use final in java. Val is constant variable.

Example:


val x = 25
//first inialised the value of x
print(x)

//can not change the value of x because x is immutable
 x= 26
// compile time error Val cannot be reassigned
print(x)

Output:
Error : Kotlin:  Val cannot be reassigned
      

No comments:

Post a Comment