Running your first Kotlin program

Now that we have our command-line compiler set up, let's try it out with a simple Kotlin program. Navigate to your home directory and create a new file named Hello.kt. All Kotlin files have a .kt extension appended to the end of the filename.

Open the file you just created in a text editor of your choosing and input the following:

// The following program prints Hello world to the standard system output.
fun main (args: Array<String>) {
println("Hello world!")
}

Save the changes made to the program file. After the changes have been saved, open your terminal window and input the following command:

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

The preceding command compiles your program into an executable, hello.jar. The -include- runtime flag is used to specify that you want the compiled JAR to be self-contained. By adding this flag to the command, the Kotlin runtime library will be included in your JAR. The -d flag specifies that, in this case, we want the output of the compiler to be called.

Now that we have compiled our first Kotlin program, we need to run it—after all, there's no fun in writing programs if they can't be run later on. Open your terminal, if it's not already open, and navigate to the directory where the JAR was saved to (in this case, the home directory).  To run the compiled JAR, perform the following:

java -jar hello.jar

After running the preceding command, you should see Hello world! printed on your display. Congratulations, you have just written your first Kotlin program!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.242.235