Search code examples
kotlinkotlin-multiplatform

Kotlin multiplatform check execution platform within common code


I have a common module that is consumed by JVM, JS, and Native projects. Within the common module, I would like to do something like the following:

fun currentPlatform(): String {
  // return "JVM", "JS", or "Native" depending on where this code is executing.
}

Solution

  • In the common module, I have

    enum class KotlinPlatform {
     JVM,JS,Native
    }
    expect val currentPlatform: KotlinPlatform
    

    In the JVM module, I have:

    actual val currentPlatform = KotlinPlatform.JVM
    

    And the above can be repeated for JS and any other modules as well.