Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

Difference between Delegates.notNull and lateinit Kotlin

I am very confused both looks and works pretty similar. Which one should I go for?

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

or

lateinit private var mMediaController: MediaControllerCompat

Usage:

    @Subscribe
    fun connectToSession(token: MediaSessionCompat.Token) {
         mMediaController = MediaControllerCompat(activity, token)
         mMediaController.registerCallback(mMediaControllerCallback)
    }
question from:https://stackoverflow.com/questions/44205389/difference-between-delegates-notnull-and-lateinit-kotlin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...