Delaying Initialization

Wherever it is declared, a class property must be initialized when the class instance is constructed. This rule is an important part of Kotlin’s null safety system, because it means that all non-nullable properties of a class are initialized with a non-null value when the constructor for that class is called. When you instantiate an object, you can immediately reference any property on that object, from within or outside of the class.

Despite its importance, you can bend this rule. Why would you? Because you do not always have control over how or when a constructor is called – which often happens with frameworks and libraries like Android, Spring, and JUnit.

Late initialization

Sometimes, you will find ...

Get Kotlin Programming: The Big Nerd Ranch Guide, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.