Kotlin: Run a Program Using Compiler
In this article, I will walk you through the steps to run a Kotlin program using the Kotlin compiler.
I will start by answering some basic questions in brief.
What is a compiler?
A compiler is a program that converts human-readable code (Source Code) into machine-understandable code (Byte Code).
What is Kotlin’s compiler?
The name of the Kotlin compiler is kotlinc.
How does a Kotlin compiler work?
Similar to Java, where the Java compiler (javac) takes the Java source code and compiles it into byte code(.class), Kotlin compiler (kotlinc) takes the Kotlin source code and compiles it into byte code(.class), and that byte code is run on the Java Virtual Machine (JVM).
In case there is any Java code in the Kotlin file (.kt), it will be compiled by the JVM.
Kotlin is 100 % interoperable with Java
To get started you need to install Kotlin command-line compiler. Every Kotlin release ships with a standalone version of the compiler. You can download the latest version from GitHub.
Manual Install
Unzip the standalone compiler from the above link into a directory and optionally add the bin directory to the system path. The bin directory contains the scripts needed to compile and run Kotlin on Windows, OS X, and Linux.
Homebrew
Alternatively, on OS X you can install the compiler Homebrew.
$ brew update
$ brew install kotlin
Snap package
If you use Snap-on Ubuntu 16.04 or later, you can install the compiler from the command line.
$ sudo snap install --classic kotlin
That is it for the setup.
Create and run an application
Create a simple application in Kotlin that displays “Hello, Kotlin!”. In your favorite editor, create a new file Hello.kt with the following lines:
fun main() {
println("Hello, Kotlin!")
}
Compile the application using the Kotlin compiler.
Open the terminal and go to the directory where you have saved your Kotlin program. The following command converts the Kotlin program into a jar file.
$ kotlinc Hello.kt -include-runtime -d Hello.jar
Explanation:
- -include-runtime: By default, Kotlin compiles to Java. It will require Java libraries to run at runtime. So, to include libraries required by Kotlin at runtime, you need to write this.
- -d Hello.jar: A jar file will be created, with this name.
To execute the generated jar file, run the following command.
java -jar Hello.jar
And, that is it, you will see “Hello, Kotlin!” printed in the console.
I will be maintaining a Github Repository of DS / Algorithms written in Kotlin. Check it out!