Kotlin/Native

In addition to JVM, JavaScript, Android devices, iOS, and Raspberry Pi, you can target your Kotlin code to native platforms like Windows, Mac OS, and Linux. The Kotlin compiler’s front end compiles your Kotlin code to an intermediate representation. Kotlin/Native is an LLVM-based back end of the compiler that targets the intermediate representation to self-contained programs that can run natively without a virtual machine. Your Kotlin code can interoperate with native libraries—for example, code written using the C language, Objective-C, and Swift. You can use this option to create fast running native applications and to interoperate with native libraries.

In this appendix, we’ll take a look at a small example that illustrates compiling Kotlin code to target MacOS. To target the example to other operating systems, refer to the toolchain requirements on the Kotlin/Native website.

Downloading native environment

To compile Kotlin code to native platform, you need the Kotlin/Native compiler. Download it from the binary distribution website. Once you install it, add the bin directory that contains the tools like cinterop and kotlinc-native to the path.

To get a glimpse of the power of Kotlin/Native, let’s create a small function in C and then call it from within Kotlin code. As a first step, let’s create a C header file named fib.h under a c directory.

// fib.h
int fib(int n);

The header file declares a function named fib() that takes an integer value and returns an integer value.

Next, let’s implement this function in a file named fib.c, also placed in the c directory:

Get hands-on with 1200+ tech skills courses.