What is the best way to apply platform specific annotations in Kotlin Multuplatform?

Viewed 109

I have some data transfer class which I want to share between platforms. There is only one difference. The implementations have different annotations on different platforms. What is the best way to do it? I know the only one way.

In the commonsMain:

expect class ErrorMessage (message: String = "") : DataTransferObject {
    var message: String
}

In jvmMain:

@SomeJvmAnnotation
actual class ErrorMessage actual constructor (actual var message: String) : DataTransferObject

But if I implement every class this way than there is no profit from KMM. This way I need to implement every class n + 1 times where n is a number of platforms. Is there a simpler way to apply different annotations?

May be there is a way not to put expect on class.

1 Answers

Not the greatest solution, but you can use actual and expect to define your platform-specific annotations.

I used it to ignore unit tests only on the JS runtime.

commonMain

 ​/*​* 
 ​ * Ignore a test when running the test on a JavaScript test runtime. 
 ​ ​*/ 
 ​@Target( ​AnnotationTarget​.​CLASS​, ​AnnotationTarget​.​FUNCTION​ ) 
 ​expect​ ​annotation​ ​class​ ​JsIgnore​()

jsMain

 ​actual​ ​typealias​ ​JsIgnore​ ​=​ kotlin.test.​Ignore

jvmMain

 ​// Nothing to do. This should only ignore tests on the JavaScript test runtime. 
 ​actual​ ​annotation​ ​class​ ​JsIgnore

I guess whether or not this is appropriate for you will really depend on the specific annotations you need for each platform, and to which degree they semantically overlap.

Related