Getting Exception when Safe-Casting to Generic Type in Kotlin
3
I am using safe casting option in kotlin i.e. as? still i am getting class cast exception when the data types are not compatible, this is happening when i am doing this via a generic method written to perform case, however if i directly perform the cast it returns null as expected from a safe cast class CastTest(val data: Any) { fun castViaGenericMethod(): TypeA? { return castToContext<TypeA>() } fun castDirectly(): TypeA? { return data as? TypeA } private fun <CONTEXT> castToContext(): CONTEXT? = data as? CONTEXT } castViaGenericMethod() -> this method throws ClassCastException when data is not TypeA type. castDirectly() -> this returns null when the cast is not possible. Please suggest how can this be done.