https://kotlinlang.org logo
f

Fabio

09/10/2020, 5:56 AM
Often when I try to handle generics I run into this casting situation, which generates a warning that I don't understand:
Copy code
abstract class TodayDynamicModel<V : View> : BardeenListUiModel() {

    fun asTodayDynamicModel() = this as TodayDynamicModel<View> // --> Unchecked cast: TodayDynamicModel<V> to TodayDynamicModel<View>
}
Isn't
V
guaranteed to be of type
View
?
k

Kroppeb

09/10/2020, 9:19 AM
This is only valid if you use
TodayDynamicModel<out V:View>
f

Fabio

09/14/2020, 1:14 AM
@Kroppeb also, then I can't write
Copy code
abstract class TodayDynamicModel<out V : View> : BardeenListUiModel() {
    abstract fun bindView(view: V) // Type parameter V is declared as 'out' but occurs in 'in' position in type V
And if I do
<in V: View>
I can't do
abstract fun buildView(context: Context): V?
full class for disclosure (it's a variation of RecyclerView btw, and I changed the name since original post)
Copy code
abstract class BardeenDynamicRecyclerViewModel<V : View> : BardeenListUiModel() {

    abstract fun bindView(view: V?)

    abstract fun buildView(context: Context): V?

    @Suppress("UNCHECKED_CAST")
    fun asTodayDynamicModel() = this as BardeenDynamicRecyclerViewModel<View>

    fun buildAndBindView(context: Context): V? {

        return buildView(context)
            .also {
                bindView(it)
            }
    }
}
found the solution, I added
out V:View
in
fun asTodayDynamicModel() = this as BardeenDynamicRecyclerViewModel<out View>
and in a bunch of places that call
asTodayDynamicModel
.
3 Views