kotlin - Delegates.notNull 和 lateinit Kotlin 的区别

标签 kotlin

我对外观和工作方式都非常相似感到非常困惑。我应该去哪一个?

private var mMediaController by Delegates.notNull<MediaControllerCompat>()

lateinit private var mMediaController: MediaControllerCompat

用法:

    @Subscribe
    fun connectToSession(token: MediaSessionCompat.Token) {
         mMediaController = MediaControllerCompat(activity, token)
         mMediaController.registerCallback(mMediaControllerCallback)
    }

最佳答案

这两种模型相似,一种比另一种早。 Delegates.notNull() ( api reference ) 基于 delegated properties并且是原始的,后来出现了 lateinit ( Late Initialized Properties )。既不涵盖所有可能的用例,也不应使用,除非您可以控制类的生命周期并确定它们会在使用前被初始化。

如果支持字段可以直接设置,或者您的库无法使用委托(delegate),那么您应该使用 lateinit 并且通常它是大多数人在使用依赖注入(inject)时的默认设置。 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.

如果 lateinit 不支持您使用的类型(不支持原始类型),那么您将被迫使用委托(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.

您可能还想阅读讨论主题“ Improving lateinit ”。

关于kotlin - Delegates.notNull 和 lateinit Kotlin 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44205389/

相关文章:

java - 为什么 Spring Boot(在 Kotlin 中)无论如何总是返回状态代码 200?

Kotlin Gradle - java.lang.NoClassDefFoundError : org/jetbrains/kotlin/konan/target/KonanTarget

constructor - 无法编译内部构造函数调用原因 :Primary constructor call expected

kotlin - 如何使用 Dagger 2 注入(inject) Kotlin 委托(delegate)属性?

gradle - Kotlin编译在终端中失败,但在Intellij中失败

java - Kotlin Array 的 toList 和 asList 有何不同?

kotlin - 为什么在 Kotlin 中可以从逆变列表中读取

android - kotlin 对象使用 Firebase 的空构造函数

android - 如何在 Kotlin 中使用 anko 删除除最新 10 条记录之外的所有记录?

java - 让 Android Studio 使用 Java 而不是 Kotlin?