如何在 Kotlin Native 中使用 kotlin.system?

Arn*_*gel 2 android kotlin kotlin-native

我想使用像 getTimeMillis() 这样的系统函数,它应该是 kotlin.system 的一部分:https ://kotlinlang.org/api/latest/jvm/stdlib/kotlin.system/index.html

但是编译器说不能导入这样的模块。gradle 配置是这样的(kotlin 多平台项目):

    commonMain.dependencies {
        implementation "org.jetbrains.kotlin:kotlin-stdlib-common:1.3.10"
        implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.10.0"
        implementation "io.ktor:ktor-client:1.0.0"
        implementation "io.ktor:ktor-client-logging:1.1.0"
        implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core-common:1.1.0"
    }
Run Code Online (Sandbox Code Playgroud)

我也找不到任何使用示例或此模块。

Ale*_*ger 5

getTimeMillis()仅适用于JVMNative不适用于CommonJS

如果您只是在getTimeMillis()Native 模块的源目录中调用,则编译器可以找到该函数。

如果您需要调用,则Common必须自己实现Common包装器函数并自己在每个平台上实现包装器。

为此,请创建一个存根函数和一个在公共模块中使用它的函数。例如:

expect fun getSystemTimeInMillis(): Long

fun printSystemTimeMillis() {
    println("System time in millis: ${getSystemTimeInMillis()}")
}
Run Code Online (Sandbox Code Playgroud)

然后在您的平台特定模块中实现该功能。例如在 JVM 模块中,如:

actual fun getSystemTimeInMillis() = System.currentTimeMillis()
Run Code Online (Sandbox Code Playgroud)

或者在本机模块中,例如:

actual fun getSystemTimeInMillis() = getTimeMillis()
Run Code Online (Sandbox Code Playgroud)

另见:https : //github.com/eggeral/kotlin-native-system-package