Implementing kotlin lazy and lateinit like functionality in Java

Vishal Ratna
2 min readMay 2, 2020

--

Photo by Júnior Ferreira on Unsplash

When I was working with kotlin, I was fascinated by the functionalities which kotlin provides, but I knew one thing kotlin gets converted into Java bytecode, so things which kotlin does must be possible in Java.

I will explain how we can achieve kotlin’s lateinit and lazy in Java. We will be limited by the Java syntax, but we can achieve the core feature.

lateinit: The whole point is to make sure that we initialize the object before we use it, or else it should throw an Exception letting us know that we are missing something in the code.

In the context of android, we can use this for data binding and view model objects. We can initialize LateInit<SomeActivityDataBinding> and use it.

1. Just like kotlin lateinits, these can not be initialized with null. If a value can be initialized with null then there is no point of late initialization. Just initialize that with null.

2. For lots of objects, we know that keeping null as initial values will not make sense but we do not know the initial values too. So, we declare them as lateinits. These objects should be initialized before they are used or else they will throw an exception, flagging issues with your program logic.

Similarly, we will try to write a Java implementation of kotlin lazy delegates.

Implementing kotlin lazy delegates in java

It uses 3 classes.

  1. Lazy — This class is the contract for lazy initializing classes. Calling get() will call the initializer(Provider/Factory) for the class. And subsequent get calls will return the store values.
  2. Provider — This class is used to eagerly create an instance of the classes, we will implement this contract in the Factory for the classes to be initialized lazily.
  3. LazyProvider — This the implementation of kotlin lazy like functionality, with mode Synchronized.

How to use it?

Using LazyProvider

As we can see, apart from creating a factory that implements the Provider interface, we can also use method references directly to initialize the LazyProvider, which reduces a lot of boilerplate code.

Just create a method that returns your instance which needs to be lazily created and pass it as a method reference to LazyProvider constructor.

So, we saw how easy it is to write the implementation of the functionalities provided in kotlin. I will come back with more such articles.

--

--

Vishal Ratna

Senior Android Engineer @ Microsoft. Fascinated by the scale and performance-based software design. A seeker, a learner. Loves cracking algorithmic problems.