Working with the command-line compiler for any language is one of the first steps to get a better understanding of the language, and this knowledge comes handy at a lot of times. In this recipe, we will run a Kotlin program using the command line, and we will also play a bit with the interactive shell of Kotlin.
To be able to perform this recipe, you need a Kotlin compiler installed on your development machine. Every Kotlin release ships with a standalone compiler. You can find the latest release at https://github.com/JetBrains/kotlin/releases.
To manually install the compiler, unzip the standalone compiler 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.
Now we are ready to run our first program using the command line. First, we will create a simple application that displays Hello World! and then compile it:
- Create a file with the name
hello.kt
and add the following lines of code in that file:
fun main(args: Array<String>) { println("Hello, World!") }
- Now we compile the file using the following command:
$ kotlinc hello.kt -include-runtime -d hello.jar
- Now we run the application using the following command:
$ java -jar hello.jar
- Suppose you want to create a library that can be used with other Kotlin applications; we can simply compile the Kotlin application in question into
.jar
executable without the-include-runtime
option, that is, the new command will be as follows:
$ kotlinc hello.kt -d hello.jar
- Now, let's check out the Kotlin interactive shell. Just run the Kotlin compiler without any parameters to have an interactive shell. Here's how it looks:
Hopefully, you must have noticed the information I am always guilty of ignoring, that is, the command to quit interactive shell is :quit
and for help, it is :help
.
You can run any valid Kotlin code in the interactive shell. For example, try some of the following commands:
3*2+(55/5)
println("yo")
println("check this out ${3+4}")
Here's a screenshot of running the preceding code:
The -include-runtime
option makes the resulting .jar
file self-contained and runnable by including the Kotlin runtime library in it. Then, we use Java to run the .jar
file generated.
The -d
option in the command indicates what we want the output of the compiler to be called and maybe either a directory name for class files or a .jar
filename.
Kotlin can also be used for writing shell scripts. A shell script has top-level executable code.
Kotlin script files have the .kts
extension as opposed to the usual .kt
for Kotlin applications.
To run a script file, just pass the -script
option to the compiler:
$ kotlinc -script kotlin_script_file_example.kts