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

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
主站蜘蛛池模板: 克东县| 琼海市| 武安市| 安溪县| 德保县| 韶关市| 松滋市| 黄梅县| 莱阳市| 瑞昌市| 涞源县| 普安县| 怀远县| 汝阳县| 石嘴山市| 济阳县| 沭阳县| 澄江县| 苏尼特左旗| 牙克石市| 调兵山市| 西乌珠穆沁旗| 遵义县| 阿尔山市| 日土县| 惠州市| 株洲县| 全州县| 项城市| 墨脱县| 松江区| 滦南县| 崇阳县| 乌兰浩特市| 井研县| 宜丰县| 定日县| 香河县| 丹寨县| 武夷山市| 塘沽区|