The var & val Of Kotlin

The Var and Val of Kotlin

There can be many versions of understanding for this topic depending on how you imply to use them. Lets start with basics. Now apparently we tend to somehow understand that names are given for a reason. In our case here it is 'var' & 'val'.

'Var' can be referred as variables. Now variables as names suggest can be varying in your code journey starting to end. I hope all this is making some sense here. Coming to 'val' that can be referred as value. Now this will not change, throughout the code value will be same. 

According to the supporting document, var is mutable sure, but that does not imply val is immutable. In more simple words, 'val' is read-only variable. 

What happens if you try to change the value of 'val' variable? 


 fun main(args: Array<String>) {  
   val marksInMaths = 74  
   print("Scored Marks in Mathematics : "+marksInMaths)  
   //now change the value  
   marksInMaths =100  
   print("\nWished to score in Mathematics : "+marksInMaths)  
 }  

This above code will throw compile-time error. Val cannot be reassigned. Now try the above same example using 'var'.  There will be no error in your code for same. 

There is no written confirmation given but we can assume here that 'val' has similar properties or rather I will say similar definition of that like 'final' variable. You assign it once and cannot change it again. So, If there are any more hidden agendas of these two which I come across I will share them. 


Comments

Popular posts from this blog

Kotlin Beginners Guide

Remove findViewById in Kotlin-Android