带`?`的可空var与lateinit var [英] Nullable var with `?` vs. lateinit var

查看:126
本文介绍了带`?`的可空var与lateinit var的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Kotlin/Android活动/片段中定义全局变量的最佳方法是什么?

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 

lateinit var viewpager: CustomViewPager

?

如果使用前者,则无需在代码中检查null.例如,如果我对以下内容使用lateinit:

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),那么我将必须检查是否为空.

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

推荐答案

使用lateinit,是说您将绝对确保在某个位置创建该变量的实例(否则,如果以下情况,您的应用程序将引发异常: lateinit尚未初始化),那么与使用null相比,该变量在整个项目的其余部分也不会为null,这意味着该对象在其余代码中可能为null.项目,您将不得不始终应对可为空性.

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.

如果您肯定不会将变量设为null且始终需要它的一个实例,请使用lateinit

If you are positive that you are not going to make a variable null and you require an instance of it always, use lateinit

问自己一个问题:

我100%确定要在此类的某个位置使用此变量的实例吗?

Am I 100% sure that I will be using an instance of this variable somewhere in this class ?

如果答案是Yes,则您可能应该使用lateinit,因为lateinit会强制您创建它的实例.

If the answer to that is Yes, you should probably be using lateinit, as lateinit forces you to create an instance of it.

如果答案为No,则您可能应该使用可为空的字段.

If the answer is No, you should probably be using a nullable field instead.

来自这里: https://www.kotlindevelopment.com/lateinit-kotlin/

lateinit关键字代表后期初始化.当在构造函数中无法提供非null的初始化器时,lateinit非常方便,但是开发人员可以肯定,访问该变量时该变量不会为null,从而避免了在以后引用它时进行null检查.

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.

这篇关于带`?`的可空var与lateinit var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆