kotlin - 在 Kotlin Multiplatform 中应用平台特定注释的最佳方法是什么?

标签 kotlin kmm

我有一些数据传输类,我想在平台之间共享。只有一处不同。不同平台上的实现有不同的注释。最好的方法是什么?我知道唯一的方法。

在公共(public)区域主要:

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

在 jvmMain 中:

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

但是如果我以这种方式实现每个类,那么 KMM 就不会带来任何利润。这样我需要将每个类实现 n + 1 次,其中 n 是平台数。有没有更简单的方法来应用不同的注释?

也许有一种方法可以不把期望放在类里面。

最佳答案

不是最好的解决方案,但您可以使用actualexpect来定义特定于平台的注释。

我用它来ignore unit tests only on the JS runtime .

通用主控

 ​/*​* 
 ​ * 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

我想这是否适合您实际上取决于每个平台所需的特定注释,以及它们在语义上重叠的程度。

关于kotlin - 在 Kotlin Multiplatform 中应用平台特定注释的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70724876/

相关文章:

java - 适用于 Mac OSX Catalina 的 Android studio 3.5 在索引进程中崩溃

android - (x..x).map 在 kotlin android 中做什么

android - 在 Android 的内部布局中设置文本字段的值

android - Kotlin Multiplatform Project的共享模块中如何使用@Parcelize注解

kotlin - 无法在 kotlin 多平台中访问预期的类构造函数参数

ios - Kotlin 多平台 (KMM) 中是否有 AES 128 加密(密码)逻辑?

android - 如何恢复协程的真实调用轨迹?

java - 无法导入@Inject 注释

android - Google Places Android 显示错误 "place fields must not be empty"?