Introduction :
For running a Kotlin program, what IDE you use ? IntellijIdea,Eclipse Visual Studio Code or anything else ? We can also run a Kotlin program using command line. If you love working with command line, you can use Kotlin compiler to compile and run a program directly. In this tutorial, we will learn how to do this. Let’s take a look :
Setup :
Setup is different for different OS. You can refer the official guide if you want or try the preferred way as I am showing below :
1. Manual setup :
Download the latest release from the Github. Make sure to download a final release, not any dev-release. You can check this page to know more about the current release.Download, unzip and add the bin directory to the system path.That’s it.
2. SDKMAN! :
Run the following two commands if you have SDKMAN! installed :
$ curl -s https://get.sdkman.io | bash
$ sdk install kotlin
3. Homebrew :
This is the most easiest way to install kotlin for Mac users.
$ brew update
$ brew install kotlin
4.MacPorts and Snap package :
If you have either MacPorts installed or using ubuntu Snap package, use the below command :
$ sudo port install kotlin
$ sudo snap install --classic kotlin
Running a application :
Kotlin files have .kt extension. First of all, create one file Example.kt and enter the below code :
fun main(args: Array) {
println("Hello World!!")
}
If you run this code, it will invoke the main function and print out the Hello World!! line. Now, use the following command :
kotlinc Example.kt -include-runtime -d example.jar
It will create one new file example.jar in the same folder. The -include-runtime option makes the .jar file self-contained and includes the kotlin runtime library in it to make it runnable. To run the .jar file, use the below command :
java -jar example.jar
It will print out Hello World!! as output .
Using Kotlin interective shell :
We can use the kotlin compiler to create a Kotlin interective cell and execute code directly in the cell. Use kotlinc to start the cell. You can use command :help to list down all available commands and :quit to quit the cell. You can use this command line to run any kotlin code.
Conclusion :
We have learn how to use command line to run Kotlin code saved in a file and how to run directly using the interective shell. Try the examples shown above and drop a comment below if you have any queries.