Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nullability assignment of generic type in kotlin methods

I’ve created this extension method for an androidx.lifecycle.LiveData:

inline fun <T> LiveData<T>.observeNotNull(crossinline observer: (T) -> Unit) {
    this.observe(viewLifecycleOwner, Observer { value ->
        value?.let { observer(it) }
    })
}

As you can see, the value passed to the observer parameter (it) can never be null. But when I call this method, the value is technically nullable, as shown in this example:

Example code of observeNotNull extension usage

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’d like to do something like crossinline observer: (T!) -> Unit, is this possible?

EDIT: the extension should work on both nullable and non-nullable livedata types. Preferably combined in 1 extension method, but ifit’s only possible when using 2 separate extension methods I’d still like to hear.

>Solution :

It depends on the concrete type that is represented by type variable T if it is nullable. If there is no further information to infer the concrete type, it is Any?, and thus it can be null. You have to define T: Any if you want to ensure that T represents a non-nullable type:

inline fun <T: Any> LiveData<T>.observeNotNull(crossinline observer: (T) -> Unit) {
    this.observe(viewLifecycleOwner, Observer { value ->
        value?.let { observer(it) }
    })
}

If you want to allow all types for T, but not for the argument of observer, then this should be possible to achieve with definitely non-nullable types in Kotlin 1.7 using notation T & Any:

inline fun <T> LiveData<T>.observeNotNull(crossinline observer: (T & Any) -> Unit) {
    this.observe(viewLifecycleOwner, Observer { value ->
        value?.let { observer(it) }
    })
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading