Lilly
09/23/2022, 5:19 PMfun <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?mkrussel
09/23/2022, 5:57 PMas 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.Lilly
09/23/2022, 6:18 PMval packet: ResponsePacket = ResponsePacket()
packet as ParameterResponsePacket // not working
val packet: ResponsePacket = ParameterResponsePacket()
packet as ParameterResponsePacket // working
An embarassing mistake 🙂