https://kotlinlang.org logo
#getting-started
Title
# getting-started
m

matt tighe

06/12/2020, 9:16 PM
Let’s say I want to define a data class over a generic type, as part of a sealed class so that I can use it like this
Copy code
when (result) {
    is SuccessDataClassWithGenericTypeOf<MyGenericType> -> doThings(it)
    is Failed -> doFailedThings(it.failureMessage)
    is Loading -> doLoadingThings
}
Why does the type get erased in this case:
Copy code
sealed class MyResultType {
    data class SuccessDataClassWithGenericTypeOf<T>(val result: T) : MyResultType()
    object Loading : MyResultType()
    data class Failed(val failureMessage: String) : MyResultType()
}
But not in this case:
Copy code
sealed class MyResultType<out T> {
    data class SuccessDataClassWithGenericTypeOf<T>(val result: T) : MyResultType<T>()
    object Loading : MyResultType<Nothing>()
    data class Failed(val failureMessage: String) : MyResultType<Nothing>()
}
k

Kroppeb

06/13/2020, 7:57 AM
The type gets erased in both cases.