using lateinit
, you are saying that you absolutely will make sure that an instance of that variable is created somewhere (otherwise, your application will throw an exception if a lateinit
has not been initialized) and then that variable also will not be null throughout the rest of your project, compared to using null
, it means that this object potentially could be null somewhere in your code for the rest of the project and you will have to deal with nullability throughout.
If you are positive that you are not going to make a variable null and you require an instance of it always, use lateinit
Ask yourself this question :
Am I 100% sure that I will be using an instance of this variable somewhere in this class ?
If the answer to that is Yes
, you should probably be using lateinit
, as lateinit
forces you to create an instance of it.
If the answer is No
, you should probably be using a nullable field instead.
Taken from here : https://www.kotlindevelopment.com/lateinit-kotlin/
The lateinit keyword stands for late initialization. Lateinit comes very handy when a non-null initializer cannot be supplied in the constructor, but the developer is certain that the variable will not be null when accessing it, thus avoiding null checks when referencing it later.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…