Kotlin Kmongo library with abstract class collection

618 Views Asked by At

I have these models

abstract class Message : Data
data class TextMessage(val m: String): Message
data class ImageMessage(val m: ByteArray): Message

and I want to get a collection by the abstract class Message

database.getCollection<Message>

But it will actually be a implement class (TextMessage, ImageMessage) instance depending on it's content

when(val value = collection.findOne()) {
    is TextMessage -> {}
    is ImageMessage -> {}
}

how to do this?

1

There are 1 best solutions below

3
On BEST ANSWER

The KMongo library has 3 options for object mapping, and your solution will depend on which one is being used.

By default, Jackson engine is used. You can use POJO Codec engine by adding a -native suffix to the artifactId, or Kotlinx Serialization by adding a -serialization suffix to the artifactId.

https://litote.org/kmongo/quick-start/#object-mapping-engine

Depending on the engine used, apply how that engine handles polymorphism: