How to use different code for different Kotlin targets?

Is it possible to have code in a kotlin project (either inline in a class, or having two versions of a file) where one version is used on on target (Kotlin/JS) and a different one on a different target (Kotlin/Native)?

Something like #if js or SomeClass.js.kt kind of thing?


  • There are expected and actual declarations that most likely are what you are searching for:

    If you're developing a multiplatform application that needs to access platform-specific APIs that implement the required functionality (for example, generating a UUID), use the Kotlin mechanism of expected and actual declarations.

    With this mechanism, a common source set defines an expected declaration, and platform source sets must provide the actual declaration that corresponds to the expected declaration. This works for most Kotlin declarations, such as functions, classes, interfaces, enumerations, properties, and annotations.

    These declarations are still officially documented as being beta features but they also claim to be almost ready, so perhaps it's worth a look: https://kotlinlang.org/docs/multiplatform-connect-to-apis.html

    Additionally you can also check this tutorial: Introduction to Multiplatform Programming in Kotlin