如何在 Kotlin Native 中使用 kotlin.system?
How to use kotlin.system with 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"
}
我也找不到任何使用示例或此模块。
getTimeMillis()
仅适用于 JVM
和 Native
,不适用于 Common
和 JS
。
如果您只是在 Native 模块的源目录中调用 getTimeMillis()
,编译器可以找到该函数。
如果您需要在 Common
中调用,您必须自己实现一个 Common
包装器函数,并自己在每个平台上实现包装器。
为此创建一个存根函数和一个在您的公共模块中使用它的函数。例如:
expect fun getSystemTimeInMillis(): Long
fun printSystemTimeMillis() {
println("System time in millis: ${getSystemTimeInMillis()}")
}
然后在您的平台特定模块中实现该功能。例如在一个 JVM 模块中:
actual fun getSystemTimeInMillis() = System.currentTimeMillis()
或者在像这样的本机模块中:
actual fun getSystemTimeInMillis() = getTimeMillis()
另请参阅:https://github.com/eggeral/kotlin-native-system-package
我想使用像 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"
}
我也找不到任何使用示例或此模块。
getTimeMillis()
仅适用于 JVM
和 Native
,不适用于 Common
和 JS
。
如果您只是在 Native 模块的源目录中调用 getTimeMillis()
,编译器可以找到该函数。
如果您需要在 Common
中调用,您必须自己实现一个 Common
包装器函数,并自己在每个平台上实现包装器。
为此创建一个存根函数和一个在您的公共模块中使用它的函数。例如:
expect fun getSystemTimeInMillis(): Long
fun printSystemTimeMillis() {
println("System time in millis: ${getSystemTimeInMillis()}")
}
然后在您的平台特定模块中实现该功能。例如在一个 JVM 模块中:
actual fun getSystemTimeInMillis() = System.currentTimeMillis()
或者在像这样的本机模块中:
actual fun getSystemTimeInMillis() = getTimeMillis()
另请参阅:https://github.com/eggeral/kotlin-native-system-package