官术网_书友最值得收藏!

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
主站蜘蛛池模板: 湘乡市| 葵青区| 军事| 合川市| 靖宇县| 尤溪县| 镇平县| 广德县| 鹿邑县| 梓潼县| 施秉县| 日照市| 乌兰察布市| 嘉祥县| 湄潭县| 镇宁| 宜州市| 邓州市| 西城区| 达州市| 常山县| 南投县| 始兴县| 枣强县| 迁西县| 蓬安县| 禹城市| 饶河县| 醴陵市| 财经| 汝州市| 贺兰县| 安阳县| 株洲县| 麟游县| 丰宁| 东阿县| 通海县| 土默特左旗| 岳阳县| 遵义县|