Purpose of "lateinit" and "by lazy" in Kotlin

"Lateinit" is a mechanism to break from Kotlin's rules on variable initialization. 

Kotlin's variable declaration syntax forces the developer to indicate if the variable is nullable (by adding an interrogation mark to the type). Additionally, a variable is mutable only if we choose to declare it with var, which then will be highlighted in the IDEA IDE. 

These safeguards are lessons learned from Java to catch as many errors as possible at compile time, but the language designers must have recognized that the developer sometimes knows better and the most reasonable choice is to have a non-nullable variable that will be initialized at a later time. Class members in JUnit test suites are a good example:


The class members are not initialized upon declaration or in a constructor and it wouldn't be wise to waste time and confuse future readers by plugging dummy objects.

"By lazy", on the other hand, is that, lazy initialization, values computed on first usage. This is a simplified version of a snippet of a real class, from one of my projects:

This class is part of an application to represent and fold origami figures. A layer is a layer of paper. A "layer stack" is a stack of layers that, only theoretically, co-exist in the same plane in the 3D space and would the folded by a same line. 

 This class has geometrical information that is used in operations such as folding or rotation, and has methods and variables related to its rendering such as the "by lazy" denoted method that returns which parts of the layer stack will be displayed at all (ie not completely hidden by other layers). 

While doing geometrical operations on the layers, the rendering information is irrelevant.

Comments