Now that we have JDK and the Kotlin compiler set up, let's try writing our first program in Kotlin and learn a few different ways to compile and run it.
Let's consider the HelloWorld.kt program, which just prints the hello message and the first argument passed to it:
fun main(args:Array<String>){
println("Hello${args[0]}")
}
There are different ways to compile and run Kotlin code:
- Command line: By including the runtime, we don't have to provide the classpath; it gets bundled into it. To bundle the JAR, execute the following command in the command prompt/console:
kotlinc HelloWorld.kt -include-runtime -d HelloWorld.jar
We pass the class name and include the runtime and the name of the JAR as command-line arguments.
In order to run the program, execute the following command:
kotlin -classpath helloworld.jar HelloWorldKt World
Alternatively, we can use the following command:
java -classpath helloworld.jar HelloWorldKt World
The output is as follows:
We can also compile Kotlin code without the runtime. When we want to run it using Java or Kotlin, we have to specify where the class file,HelloWorldKt, is located:
kotlinc HelloWorld.kt -d classes
kotlin -classpath classes HelloWorldKt World
The output is as follows:
- Read-eval-print-loop: Kotlin has an read-eval-print-loop (REPL) that we can use. Simply type kotlinc in the terminal and it will become an REPL. We can now run the Kotlin code interactively and experiment with it, as demonstrated in the following:
We can type :quit to exit the REPL.
- Scripts: We can create a script file to compile and run a Kotlin program. Create a file called HelloWorld.kts. The s in the file extension stands for script. Then add the following print statement to it:
println("Hello World from Script")
HelloWorld.kts just has one print line statement. In the console, execute the following command:
kotlinc -script HelloWorld.kts
This gives the output shown in the following screenshot:
This way, we can directly run the Kotlin file as a script.
In this section, we have learned the following:
- How to install Kotlin
- How to compile and create byte code and run it
- How to code and play with REPLs directly
- How to write Kotlin code as a script and run it