[SOLVED] I have a problem with generics: ```fun &l...
# android
[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:
The IDE marks the packet as smart casted (green background) but it isn't actually. Any ideas whats is wrong?
It is because of type erasure. The
as T
does not actually do anything since at Runtime T has been erased to
. The cast is forcing the compiler to break the type safety. If the caller actually uses the values emitted as a
will get thrown in the flow collection. I would expect at least a compiler warning at the cast though.
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