Search code examples
kotlin-multiplatform

How to deal with annotations in kotlin multiplatform data classes?


Recently I have split my KMP project into fullstack project and a core library (that is mostly consists of common data classes) and found out that I need to use an annotation from JVM library on one of the data classes that is now defined in a common module.

It doesn't seems possible to use an annotation from Java library in Kotlin common code.

What are the possible ways to resolve such issue preferrebly avoiding declaring such data class via expect and then repeating its implementation in actual platforms but with different annotations?


Solution

  • you can expect/actual the annotation it self.

    Say, if you have a JVM annotation like so, @Entity

    you can have files like src/commonMain/Entity.kt

      expect annotation class Entity()
    

    and in src/androidMain/Entity.kt

      actual typealias Entity = package.to.Entity
    

    and in src/iosMain/Entity.kt

      actual annotation class Entity()
    

    Now you can go ahead use it in your common code

    @Entity
    data class Movies(
      val title: String,
      val release: Int
    )