This post demonstrates how to compile and run Kotlin
from Windows Command Line. For Unix/Linux
, it should be quite similar.
Java Version
The examples here use Java 8
. Since we are compiling codes, we need the JDK
.
1 2 3 | java version "1.8.0_101" Java(TM) SE Runtime Environment (build 1.8.0_101-b13) Java HotSpot(TM) 64-Bit Server VM (build 25.101-b13, mixed mode) |
Download Kotlin Compiler
[wp_ad_camp_1]
To compile Kotlin codes
, we require Kotlin
compiler. Each release ships with a standalone version of the compiler.
We can download it from https://github.com/JetBrains/kotlin/releases.
Then, extract it to some directory.
Note, the src contains our .kt
source code file.
The files of interest are in kotlin-compiler-1.1.2-2/kotlinc/bin
All files that do not have file extensions are used for Unix/Linux
platforms.
Set Environment Variables
Set JAVA_HOME
When we run “java” on the Windows command line and the following happens, we need to set JAVA_HOME.
[wp_ad_camp_2]
To set JAVA_HOME, invoke the following.
1 2 | set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_101 set PATH=%PATH%;C:\Program Files\Java\jdk1.8.0_101\bin |
Set PATH to Kotlin compiler bin directory
To run any of the .bat
files from the Kotlin
compiler bin
directory from any directory, include that directory to the PATH
environment variable.
1 | SET PATH=%PATH%;C:\Users\user123\Desktop\kotlin\kotlin-compiler-1.1.2-2\kotlinc\bin |
Our Kotlin Codes
We have only one source code file.
[wp_ad_camp_3]
It has the following codes.
1 2 3 | fun main(args: Array<String>) { println("Hello, World!") } |
The codes should display "Hello, World!"
on the command line window.
Compiling Codes as Executable Jar file
Run the following command.
1 | kotlinc HelloWorld.kt -include-runtime -d HelloWorld.jar |
The key parameter to the kotlinc is the -include-runtime
. It allows us to create a jar file that is self-contained and runnable by including the Kotlin runtime
library in it.
Compiling Codes as a library
Run the following command.
[wp_ad_camp_4]
1 | kotlinc HelloWorld.kt -d HelloWorld.jar |
Notice we did not include -include-runtime
. This means the Kotlin runtime
will be needed as, for example, a maven dependency when we use the jar file.
Running our Kotlin Program
There are two ways to run it.
1 | java -jar HelloWorld.jar |
Or
1 | kotlin -classpath HelloWorld.jar HelloWorldKt |
HelloWorldKt
is from "HellowWorld.kt"
string which is the file name of our source code file.
[wp_ad_camp_5]
References
https://kotlinlang.org/docs/tutorials/command-line.html