Morning all, quick one regarding generic types. I ...
# getting-started
a
Morning all, quick one regarding generic types. I know this is a safe check (as I have only one generic here), but Kotlin will still complain about it, any way how to improve this?
Copy code
data class Test<T>(
    val key: String,
    val additionalData: T
)

inline fun <reified T> Test<*>.checkSafeCast(): Test<T>? {
    return if (this.additionalData is T) {
        this as Test<T> // Unchecked cast
    } else {
        null
    }
}
j
I guess this might be a case where you know better than the compiler, so you may want to suppress it:
Copy code
inline fun <reified T> Test<*>.checkSafeCast(): Test<T>? {
    return if (this.additionalData is T) {
        @Suppress("UNCHECKED_CAST") // the above check guarantees the safety
        this as Test<T>
    } else {
        null
    }
}
👍 1
a
Yeh I did exactly the same, I was just left wondering is there a better way - guess no. Thank you!
j
There might be another way, but it hasn't occurred to me yet :D
😅 1