Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

android - Nullable var with `?` vs. lateinit var

What is the best way to define global variables in a Kotlin/Android activity/fragment?

What are the different scenarios when you should use these 2 methods for defining a global variable:

var viewpager: CustomViewPager? = null 

or

lateinit var viewpager: CustomViewPager

?

If I use the former, I won't have to check for null in my code. For example if I used lateinit for the following:

viewpager = activity?.findViewById<CustomViewPager>(R.id.viewpager) then I would have to check for null.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...