Menu

How to run Kotlin program using compiler

How to run Kotlin program using compiler

In this tutorial, we will see how to run a Kotlin program using the compiler. Make sure you've already setup Kotlin compiler earlier.

First program in Kotlin

Open any text editor (notepad, sublime, etc.) and create a HelloWorld.kt file. Make sure that the extension of this file is ".kt". Write the following program is HelloWorld.kt file:

fun main() {
    println("Hello World")
}

Explanation:

  • Line 1: Every Kotlin program starts with the main() function. Functions are created with fun keyword in Kotlin. We'll read more about functions in later sections.
  • Line 2: println() function is used to print strings on the console.

Run Program through Command line:

Open the command prompt and go to the directory where you've saved your Kotlin program. Write the following command to convert the Kotlin program into jar file:

kotlinc HelloWorld.kt -include-runtime -d HelloWorld.jar

Explanation:

  • Kotlinc: It is the command line tool that we downloaded to run Kotlin program.
  • “HelloWorld.kt”: It is the name of your Kotlin program file.
  • -include-runtime: By default, Kotlin compiles to Java. It will require Java libraries to run at runtime. So, to include libraries required by Kotlin at runtime, we write this.
  • -d HelloWorld.jar: With this name, a jar file will be created.

To run the generated jar file, write this command:

java -jar HelloWorld.jar

You’ll see "Hello World" printed in the console.

Summary

In this tutorial, we saw how to run a program through the command line. The basic setup is complete and we will start studying about Kotlin concepts in detail from the next tutorial.


Kotlin Tutorial

AP

Abhishek Pati





Get in Touch For Details