The two models are similar, and one predates the other. Delegates.notNull()
(api reference) is based on delegated properties and was the original, and later came lateinit
(Late Initialized Properties). Neither cover all possible use cases and neither should be used unless you can control the lifecycle of the class and know for sure that they will be initialized before being used.
If the backing field might be set directly, or your library cannot work with a delegate then you should use lateinit
and typically it is the default for most people when using with dependency injection. From the docs:
Normally, properties declared as having a non-null type must be initialized in the constructor. However, fairly often this is not convenient. For example, properties can be initialized through dependency injection, or in the setup method of a unit test. In this case, you cannot supply a non-null initializer in the constructor, but you still want to avoid null checks when referencing the property inside the body of a class.
If the type you are using is not supported by lateinit
(does not support primitive types) you are then forced to use the delegate.
The (lateinit) modifier can only be used on var properties declared inside the body of a class (not in the primary constructor), and only when the property does not have a custom getter or setter. The type of the property must be non-null, and it must not be a primitive type.
You might also want to read the discussion topic "Improving lateinit".
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…