LateInit with default?


#1

Hello,

public class MyClass {
   lateinit var myList : kotlin.collections.MutableList<String>
}

I’m aware of how lateinit works. It forces a runtime exception if a property is not set to a non null value when the property is read.

Now, the reason I don’t want to simply initiize it with the default value is that these classes may be instantiated may hundreds of thousands of times, and typically, a value will be injected, in this case, we have created an object for no reason every single time, assume some of these classes can be quite heavy, even in their initial state.

What I’m really looking for is a lateinit property, that does not throw an exception if it is accessed before it is set, but rather, provides a default instance. Kind of like a lazily instatiated val.

In Java it would look like this:

public class MyClass {
  private List<String> myList;
  public List<String> getMyList() {
     if (myList == null) {
        myList = new ArrayList<String>();
     }
     return myList;
  }

  public void setMyList(List<String> list) {
     if (list != null) {
        this.myList = list;
     }
  }
}

So, what is the best way to achieve a non nullable field who we wish to set before access (typically), but who will lazily instantiate a default backing class if it is not set (rather than throwing a lateinit get before set exception)?


#2

You need to write a property delegate (I am not aware of an existing.delegate in the standard library). You can take a look at the implementation of SynchronizedLazyImpl, but note that this is a delegate for a val instead of a var.


#3

Property Delegate is your way to go