https://kotlinlang.org logo
#android
Title
# android
l

Lilly

07/21/2020, 3:59 PM
Hi, I have a channel for offering packets:
Copy code
val responsePacketsChannel = ConflatedBroadcastChannel<ResponsePacket>()
ResponsePacket is a interface because I have multiple packets which I want to offer, e.g.
ParameterPacket: ResponsePacket
or
TimePacket: ResponsePacket
. Now I'm wondering what would be the proper way to differentiate between the specific packets when I start to observe them. My first thought was using
Pair<ResponsePacketType, ResponsePacket>
combined with an enum
ResponsePacketType
->
Copy code
val responsePacketsChannel = ConflatedBroadcastChannel<Pair<ResponsePacketType, ResponsePacket>>()
Is there maybe a better solution?
j

João Gonçalves

07/21/2020, 4:02 PM
perhaps instead of interface a sealed class would be better in this case. You could then leverage where expression which forces you to exhaustively handle the various types and there you can delegate to to the specific code that handles the concrete type
l

Lilly

07/21/2020, 4:08 PM
I'm not sure if it's possible because all packets also inherit from a basic packet?!
z

Zach Klippenstein (he/him) [MOD]

07/21/2020, 4:43 PM
Even if you don't use a sealed class (which I would also recommend, sealed classes can implement interfaces), you can still use a
when
on the actual packet type, which is much better than adding the abstraction of creating an enum to represent that. Enum doesn't add any type safety, and just creates more opportunities for bugs (eg incorrect mappings, more code to update for every change, etc).
l

Lilly

07/23/2020, 9:43 AM
@Zach Klippenstein (he/him) [MOD] The problem is that some of the packet implementations are huge and they all derive from a XModemPacket :
z

Zach Klippenstein (he/him) [MOD]

07/23/2020, 3:40 PM
Not sure how size matters here. And your sealed class can extend XModemPacket.
2 Views