https://kotlinlang.org logo
w

william

06/16/2020, 1:54 AM
Any suggestions for the right approach to generics here?
Copy code
import androidx.lifecycle.MutableLiveData

class ClearableLiveData<T> : MutableLiveData<Clearable<T>>() {
    fun clear(t: T) {
        super.postValue(Clearable.Clear)
        super.postValue(Clearable.Value(t))
    }
}

sealed class Clearable<T> {
    object Clear: Clearable<Any>()
    data class Value<T>(val t: T): Clearable<T>()
}
The first call to
super.postValue
gives a type mismatch
I'm not entirely sure why not but these changes made the error go away
Copy code
sealed class Clearable<out T> {
    object Clear: Clearable<Nothing>()
    data class Value<T>(val t: T): Clearable<T>()
}
m

Michael de Kaste

06/16/2020, 8:45 AM
Clearable<Any> expects a type parameter; but since it's a singleton object you'll need Nothing because Nothing is a child of everything.
k

Kroppeb

06/16/2020, 11:15 AM
the out is important too though. without it
Clearable<Nothing>
isn't a subtype of
Clearable<T>
w

william

06/16/2020, 12:11 PM
@Kroppeb could you explain that part any more? i don't quite understand it
it sounds like this: Since we are using
out T
, any of the type parameters can be a supertype of
T
, which
Nothing
is a supertype of everything.
k

Kroppeb

06/16/2020, 1:31 PM
You might wanna start reading here https://kotlinlang.org/docs/reference/generics.html
w

william

06/16/2020, 2:59 PM
i have - is my assumption above incorrect? @Kroppeb
k

Kroppeb

06/16/2020, 3:01 PM
Since we are using
out T
, any of the type parameters can be a subtype of
T
, which
Nothing
is a subtype of everything.
w

william

06/16/2020, 4:41 PM
ok so almost had that one then
thanks