- Kotlin for Enterprise Applications using Java EE
- Raghavendra Rao K
- 379字
- 2021-06-10 18:49:18
Compiling and running
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
- Learning C# by Developing Games with Unity 2020
- What's New in TensorFlow 2.0
- Computer Vision for the Web
- PHP+MySQL網(wǎng)站開發(fā)技術(shù)項(xiàng)目式教程(第2版)
- 軟件測(cè)試項(xiàng)目實(shí)戰(zhàn)之性能測(cè)試篇
- Vue.js 3.0源碼解析(微課視頻版)
- OpenStack Cloud Computing Cookbook(Fourth Edition)
- 精通Python自然語言處理
- C語言開發(fā)基礎(chǔ)教程(Dev-C++)(第2版)
- Python Data Structures and Algorithms
- D3.js By Example
- Solr Cookbook(Third Edition)
- Python 3.7從入門到精通(視頻教學(xué)版)
- Managing Microsoft Hybrid Clouds
- R的極客理想:量化投資篇