kotlin - Delegates.notNull和lateinit之间的差异

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".

译文

这两个模型是相似的,Delegates.notNull()(api参考)基于委托属性,是原始的
,后来是lateinit(后期初始化属性)。不覆盖所有可以能的用例,除非你能够控制类的生命周期,并确保它们在使用前初始化。

如果可以以直接设置备份字段,或者者你的库不能使用委托,那么你应该使用lateinit。来自文档的:

通常,声明为非空类型的属性必须在构造函数中初始化。然而,这通常是不方便的。例如可以通过依赖项注入或者单元测试的设置方法来初始化属性。在这种情况下,不能在构造函数中提供非空初始值设定项,但是在引用类中的属性时仍然要避免null检查。

如果lateinit(不支持基元类型)不支持你正在使用的类型,则强制你使用委托。

(lateinit)修饰符只能在类(不在主构造函数中)内声明的var属性上使用,而且只有在该属性没有自定义集合或者设置器时。属性的类型必须是非空的,并且不能是基元类型。

猜你喜欢

转载自blog.csdn.net/hewenlee/article/details/83753411
今日推荐