带有 `?` 的可空变量 vs. lateinit var [英] Nullable var with `?` vs. lateinit var

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

问题描述

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

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

当您应该使用这 2 种方法来定义全局变量时,有哪些不同的场景:

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(R.id.viewpager) 那么我将不得不检查是否为空.

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

推荐答案

using lateinit,您是说您绝对会确保在某处创建该变量的实例(否则,您的应用程序如果 lateinit 尚未初始化,则将抛出异常),然后该变量在项目的其余部分也不会为空,与使用 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 关键字代表后期初始化.当构造函数中不能提供非空初始化器时,lateinit 非常方便,但开发人员确定访问时该变量不会为空,从而避免以后引用时进行空检查.

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.

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

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