Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use kotlin.system with Kotlin Native?

I'd like to use system functions like getTimeMillis() which should be a part of kotlin.system: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.system/index.html

But the compiler says such module cannot be imported. The gradle configuration is like this (kotlin multiplatform project):

    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"
    }

Also I cannot find any example of usage or this module.

like image 289
Arnie Schwarzvogel Avatar asked Oct 18 '25 08:10

Arnie Schwarzvogel


2 Answers

getTimeMillis() is only available for JVM and Native not for Common and JS.

If you but the call to getTimeMillis() in the source directory of the Native module the compiler can find the function.

If you need the call to be in Common you have to implement a Common wrapper function on your own and implement the wrapper on each platform yourself.

In order to do this create a stub function and a function which uses it in your common module . For example:

expect fun getSystemTimeInMillis(): Long

fun printSystemTimeMillis() {
    println("System time in millis: ${getSystemTimeInMillis()}")
}

Then implement that function your platform specific modules. For example in a JVM module like:

actual fun getSystemTimeInMillis() = System.currentTimeMillis()

Or in a native module like:

actual fun getSystemTimeInMillis() = getTimeMillis()

See also: https://github.com/eggeral/kotlin-native-system-package

like image 127
Alexander Egger Avatar answered Oct 20 '25 23:10

Alexander Egger


In case anyone gets here that is using kotlin native (as the title says) the solution is to add an import:

import kotlin.system.getTimeMillis;

Thanks,

like image 21
Peter Quiring Avatar answered Oct 20 '25 23:10

Peter Quiring