Member preview

Kotlin variable, to be Lazy, or to be Late?

In Kotlin, we are now introduced to two new features of an old concept, lazy initialization i.e. the deferring of an variable initialization to a later time. This is a very handy feature, as we don’t need to initialize something that until we need it, or simply because we can’t initialize something until we have all we need.

Let me first introduce the two syntactically

Initialization by Lazy

val myUtil by lazy {
MyUtil(parameter1, parameter2)
}

The above code is initializing a MyUtil object. But this will only be done upon the first usage of myUtil.

Late Initialization

lateinit var myUtil: MyUtil

and somewhere in one of the function

myUtil = MyUtil(parameter1, parameter2)

The code basically differs the initialization until when it is initialize.

Why two? Use cases?

Though both have the same concept, but are actually very different in nature. Simply looking at the variable type, one is val (immutable) and the other is var (mutable). This itself speaks much. Below are some cases of typical use

Single Instance of Variable

Sometime, we only need a single instance of a variable, and all other sharing this variable

MyUtil getMyUtil() {
if (myUtil == null) myUtil = new MyUtil(param1, param2);
return myUtil;
}

This is pretty handy for Singleton pattern, and we ensure we share the same object for all access. It also ensure we only create the object when needed. In this case, Lazy Initialization will do the trick

Initialize a Non-nullable Variable

In Kotlin, we have to define upfront if our variable is nullable or not. This would aid the compiler flag potential null object being used during compile time, and prevent Null Pointer Excpetion.

So for a member variable that is Non-nullable, when the class is created, it needs to set to something other than null. If we already have all the needed dependents during construction of class, this is not a problem. Unfortunately at times the dependents (e.g. in our example are param1 and param2) are only available at later time. Hence we are now in dead-lock, as we can’t have the variable initialize as null at start (as Kotlin will nag), and yet we have to wait till we have all the dependents object.

With this, lateinit came in handy, where Kotlin now gracefully allow it to be uninitialize during declaration, and we could get it initialize later when we have the dependents objects.

Dependency Injected Variable

If you use Dependency Injection Framework on Kotlin (e.g. Dagger2), the variable that though it’s declare upfront can’t be initialized. Hence lateinit is needed to ensure the variable will be initialized later.

@Inject
lateinit var myUtil: MyUtil

In fact, lateinit was explicitly introduced in Kotlin for this purpose.

When to use what?

The above examples are just few scenario. You could in fact use them in more scenario, as long as they are non-nullable variable. There are some simple rules to determined if you should use one or the other

  1. If they are mutable (i.e. might change at a later stage) use lateInit
  2. If they are set externally (e.g. need to pass in some external variable to set it), use lateinit. There’s still workaround to use lazy but not as direct.
  3. If they are only meant to initialized once and shared by all, and it’s more internally set (dependent on variable internal to the class), then use lazy. Tactically, you could still use lateinit, but using lazy would better encapsulate your initialization code.

Thinking over it, without considering the mutability control, lateinit is super-set of lazy i.e. you could basically use lateinit for the scenario that need to be lazy but not vice-versa. But one should use lazy instead of lateinit when possible… as lateinit exposes more codes logic in the function and messier than lazy, which hides the detail away in it’s own encapsulation, and safer.

So in short for variable initialization, be lazy if you can, else be late… last resort, do the hard way, at the start. It’s best to be lazy, Bill likes them.

“I choose a lazy person to do a hard job. Because a lazy person will find an easy way to do it.” ~Bill Gates

I hope you appreciate this post and it’s helpful for you.

You could check out my other interesting topics here.

Follow me on medium, Twitter or Facebook for little tips and learning on Android, Kotlin etc related topics. ~Elye~

Like what you read? Give Elye a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.