https://kotlinlang.org logo
l

Lilly

09/23/2022, 5:19 PM
[SOLVED] I have a problem with generics:
Copy code
fun <T : ResponsePacket> subscribe(..) : Flow<T> {
    val packet = ResponsePacket()
    emit(packet as T)
    println("what is T: ${packet.javaClass}") // prints ResponsePacket
}

caller side:
dao.subscribe<ParameterResponsePacket>()
The IDE marks the packet as smart casted (green background) but it isn't actually. Any ideas whats is wrong?
m

mkrussel

09/23/2022, 5:57 PM
It is because of type erasure. The
as T
does not actually do anything since at Runtime T has been erased to
ResponsePacket
. The cast is forcing the compiler to break the type safety. If the caller actually uses the values emitted as a
ParameterResponsePacket
a
ClassCastException
will get thrown in the flow collection. I would expect at least a compiler warning at the cast though.
l

Lilly

09/23/2022, 6:18 PM
I'm not sure if erasure is the cause of the problem or if it is a problem on top of the actual problem. I'm trying to cast the base class to derived class which is not working possible:
Copy code
val packet: ResponsePacket = ResponsePacket()
packet as ParameterResponsePacket // not working

val packet: ResponsePacket = ParameterResponsePacket()
packet as ParameterResponsePacket // working
An embarassing mistake 🙂
1