Understanding Kotlin — Part 3

Balaji S B
Proggy Blast
Published in
2 min readDec 2, 2020

This article is focusing on variable declaration in kotlin. If you are new to kotlin please check out my previous article Part 2, Part 1 here. Ok let’s get started to the topic.

In general we can declare variables with three types.

  1. Nullable initialization
  2. lazy initialization
  3. lateinit initialization

Nullable Initialization :

In kotlin offers to declare variable with mutable and immutable with nullable. We can declare the immutable nullable with val keyword and mutable nullable with var keyword. Start with visiblity modifier(optional) val/var keyword followed by type and declare with ?=null.

Lazy Initialization :

The evaluation of lazy properties is synchronized. The value is computed only in one thread and all the threads use the same value. In this whenever the value is accessed on that time the property’s lazy block is executed.

The output of the above example is “computed!”, “Hello”, “Hello”. Once the block is initialized and next time accessing the property it will return the same value again. For the lazy initialization we can use the val keyword only. We can’t use var keyword with lazy.

Lateinit Initialization :

Initializing the value of the property on the later stage is achieved with the help of lateinit modifier. Adding the lateinit modifier with var keyword only, to prevent initializing null declaration.

We can check the lateinit variable is initialized or not with the help of the following code.

Conclusion :

So from this article we come to know how to declare variable with different types and checking the variable initializated or not also. Please do clap (👏) if you like this post. Thanks and Cheers.

#Kotlin #proggyblast #balajisb Balaji S B Proggy Blast

--

--

Balaji S B
Proggy Blast

Technical Lead @ Happeist Minds Technologies Pvt Ltd