Imagine we have a websocket server that can send v...
# getting-started
i
Imagine we have a websocket server that can send various message types (defined as strings). Now for each of these received messages we need to create instance of specific class. I was able to model this data using sealed interface and enum class:
Copy code
sealed interface WebSocketMessage {
    data class Hello(data: String):WebSocketMessage
    data class Bye(data: String):WebSocketMessage
}

enum class WebSocketMessageType(val type: String, val kotlinClass: KClass<out WebSocketMessage>) {
    HELLO("hello", WebSocketMessage.Hello::class),
    BYE("bye", WebSocketMessage.Bye::class),
}

// get message
val webSocketMessageType = enumValues<WebSocketMessageType>().firstOrNull { it == type }
...
I wonder if there is a way to model this using one entity, so adding the new messages types require change in a single place 🤔
s
@igor.wojda https://stackoverflow.com/questions/34340450/how-to-get-a-kotlin-kclass-from-a-package-class-name-string/34340492 you don’t need to type them manually , but I would pay attention to what kind of messages I’m receiving and what kind of classes are allowed to be created
t
@salah This will only work on JVM @igor.wojda I recommend using serialization, see - https://kotlinlang.org/docs/serialization.html#example-json-serialization It supports polymorphism - https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md
👍 2