我对外观和工作方式都非常相似感到非常困惑。我应该去哪一个?
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/