Followers

Declaring Variables in Kotlin

Declaring Variables in Kotlin with examples 

The syntax for declaring any variable in Kotlin goes with "var" or "val", lets dive in to see a clear picture of its usage


Difference between val and var

val - It  is immutable reference i.e the value cannot be changed once assigned which is similar to final variable 
var - It is mutable reference i.e the value can be changed later as needed

Let me walk you through how and when to declare the variables


When to use val 

Read only Variables i.e can be assigned only once. If a variable is needed to be assigned only once, use "val"


case 1 - Type not Required

val str : String = "Hello"
Type is not required when the variable is initialized immediately so instead of using the above syntax one can follow as the one provided further
val str = "Hello" // Type String is automatically deduced


case 2 - Type Required

Type is required when the variable is not initialized immediately. Also this syntax can be used only when used inside the same method and cannot be declared outside.
For say it can be declared so in oncreate method but not outside at the top where the variables are usually declared.
val str : String
str = "Hello"


When to use var

Variables that can  be reassigned - can be assigned any number of times later when needed. If a variable is to be reassigned, use "var"


case 1 - Type not required

Type is not required when the variable is initialized immediately
var str = "Hello"
str = "Text Modified"


case 2 - Type Required 

Type is required when one wants the variable to be initialized later as needed in code and in this case you can use lateinit or nullable
lateinit var str :String
later in code you can initialize str = "Text Modified"
(or)
var str:String?=null


Example of Declaring variables of Primitivie Types 

val count = 5
var a=1
a=2

If you do not want to initialize the values immediately then use lateinit or nullable types
lateinit mytext :String
var mytext:String?=null


Example of Declaring views  

If a view is to be declared and accessed inside oncreate and on button click use
val textView = findViewById<TextView>(R.id.textViewid) 


If the view is to be used outside onCreate and there is a need to access it elsewhere in the activity/fragment then use "lateint"
lateinit textview : TextView and then later initialize it, remember if accessed without initialization will throw null pointer exception


Please do share your thoughts and any queries on this post in the comments below and please do like my post by giving +1 and  by sharing it. 

Post a Comment

0 Comments