Monday, April 13, 2020

compile and run Kotlin from command line

Prerequsite: Kotlin runs on jvm, which means java runtime is required to run it.
Install sdkman from command line if it is not installed yet.
curl -s https://get.sdkman.io | bash
Install Kotlin using the command sdk from the command line.
sdk install kotlin
Create a new file hello.kt
fun main(args: Array<String>) {
    println("Hello World!")
}
Compile the Kotlin code using the kotlin compiler.
kotlinc hello.kt -include-runtime -d hello.jar
Compile multiple Kotlin files. Put all the Tutorial Kotlin files between kotlinc and -include-runtime, or use the wildcard (*.kt) to include all Kotlin files in the current directory. Only one Kotlin file should have the main() function, or you will get error when running the jar file in the next stop.
kotlinc greeting.kt hello.kt -include-runtime -d hello.jar

compile and run Kotlin from command line

Run the Kotlin code on jvm using the java command.
java -jar hello.jar
Create shortcut for compiling and running Kotlin program
Find out the Kotlin binary executables
which kotlin
Add the following to the ~/.bash_profile file, replace the bin path with yours using vim editor vim ~/.bash_profile
export PATH=$PATH:/Users/yourmacosusername/.sdkman/candidates/kotlin/current/bin/
function kotlinr() {
  echo Compiling, please wait...
  kotlinc $1 -include-runtime -d out.jar
  java -jar out.jar
}
Apply the updates in the ~/.bash_profile file.
source ~/.bash_profile 
Now you can compile and run your Kotlin programs at at the same time like this:
kotlinr hello.kt
Tags: Kotlin Compile Kotlin using command line,Install, compile and run Kotlin from command line,Working with the Command Line Compiler - Kotlin,Using the command line to compile and run Kotlin code 

No comments:

Post a Comment