Search code examples
kotlinkotlin-multiplatformkotlin-native

"#ifdef" compilation condition for Kotlin/Native


I'm writing a Kotlin/Native application targeted for Windows, Linux and Mac and I need to call platform.posix._popen on Windows and platform.posix.popen on the other.

If I use a simple conditional (if (Platform.osFamily == OsFamily.WINDOWS)), I get a compile error.


Solution

  • There is no such thing as #ifdef in Kotlin, but you can use the expect/actual mechanism to achieve what you need.

    In common code, define an expect fun without a body, and then define an actual fun implementation separately in linux/windows/macOS source sets.

    You can find more details about how to do this in the Kotlin multiplatform documentation.