Kotlin Tip #24: Use lateinit
for Late Initialization of Non-null Variables — 100 Kotlin Tips in 100 Days
Twitter | LinkedIn | YouTube | Instagram
Tip #23: Use type aliases to provide alternative names for existing types
One of the Kotlin language’s core principles is its emphasis on null safety, aiming to eliminate the dreaded NullPointerException from your code. However, there are scenarios where you cannot initialize a variable at the point of declaration but are confident it will be initialized before use. For these cases, we can use thelateinit
keyword.
The lateinit
modifier allows you to declare non-null properties without immediately initializing them, providing a promise that they will be initialized before any operations are performed on them. This feature is particularly useful for dependency injection, unit testing, or initializing variables that depend on some configuration not available at the object's construction time.
You declare a lateinit
variable by placing the lateinit
keyword before the variable type. Note that lateinit
can only be used with mutable variables (var
) and with types that are non-nullable and not primitive.
class MyClass {
lateinit var dependency: SomeDependencyClass
}
Consider a scenario where you have a class that requires a context or configuration to initialize its properties. With lateinit
, you can simplify the initialization process:
In the above example, userConfig
is a non-null, uninitialized property. It gets initialized through the initializeWithConfig
method.
However, bear in mind that if you try to access the property before initialization, you will get a UninitializedPropertyAccessException
.
That's why The processUser
method checks if userConfig
is initialized, ensuring the class is used correctly.
lateinit
is a testament to Kotlin's flexibility, offering a balance between null safety and practical usability. It simplifies handling late-initialized properties while keeping the code safe and concise.
I hope you have enjoyed this tip of our series! Don’t forget to subscribe and stay tuned for more Kotlin tips!
Stay curious!
Tip #25: Use
check()
for precondition validation in your code
Contribute
Writing takes time and effort. I love writing and sharing knowledge, but I also have bills to pay. If you like my work, please, consider donating through Buy Me a Coffee: https://www.buymeacoffee.com/RaphaelDeLio
Or by sending me BitCoin: 1HjG7pmghg3Z8RATH4aiUWr156BGafJ6Zw
Follow Me on Social Media
Stay connected and dive deeper into the world of Kotlin with me! Follow my journey across all major social platforms for exclusive content, tips, and discussions.