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
Joffrey
09/24/2021, 12:39 PM
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
antoniomarin
09/24/2021, 12:45 PM
Yeh I did exactly the same, I was just left wondering is there a better way - guess no. Thank you!
j
Joffrey
09/24/2021, 12:47 PM
There might be another way, but it hasn't occurred to me yet :D