Any suggestions for the right approach to generics...
# announcements
w
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
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
the out is important too though. without it
Clearable<Nothing>
isn't a subtype of
Clearable<T>
w
@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
You might wanna start reading here https://kotlinlang.org/docs/reference/generics.html
w
i have - is my assumption above incorrect? @Kroppeb
k
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
ok so almost had that one then
thanks