What is the best way to write if null then initialize it?

I won’t.
Creating a list is not that expensive.
Therefor i would prefer to set the list in the field immediately if you don’t have to check if it’s null.

Just a couple of lines I came up with in a matter of minutes:

  • If it’s normal for the type to be null during the logic, use nullable.
  • Else if the variable is set from outside the class, use lateinit.
  • Else if the variable can be set without parameters known at class creation:
    • if the variable-creation is heavy and not always needed: use Lazy
    • else create immediately
  • If creating the variable does need parameters that aren’t known during class initialization:
    • Can you use SingleTonHolder or a similar pattern? use it.
      Also check if the class refering to the variable is secretly standalone and should be placed in a different class
  • Else use lateinit

This is only a quick thought and definately incomplete, if not plain wrong.

2 Likes