Compiling and running Kotlin

Kotlin started as a JVM language, so the first compiler for Kotlin was targeting Java bytecode. But now, there are also compilers that can turn Kotlin into JavaScript and one that is still experimental, that produces native code.

Thanks to this compiler and the native code output, soon it will be possible to write apps with Kotlin that don't require additional runtimes.

This book will focus on Kotlin running on JVM, as this is the most popular usage of Kotlin today. But most of the things learned here can also be applied to other Kotlin platforms (both JavaScript and Native).

Kotlin source code is stored in files with a .kt extension, similar to the way that Java's are stored with a .java extension. Compiling Kotlin .kt files produces .class files that contain Java bytecode.

These are the same .class files that a Java compiler produces.

From there, .class files are bundled inside .jar files to form a module (a library or an app).

Since JVM only knows about Java bytecode, running apps written in Kotlin is no different from how they are written in Java.

One additional step is needed to run Kotlin modules or apps. Kotlin has its own standard library, which builds upon Java's Standard Library, and it has to be distributed with your module or app. Luckily, the Kotlin compiler does this step for us (if you are using the compiler from the command-line, just add the -include-runtime argument to a kotlinc command). Also, with the size of around 800 KB, we can say that the Kotlin standard library is relatively small and you shouldn't be worried about it.

The following diagram shows how Kotlin source code is compiled and run on the JVM:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.36.221