English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin Compilation via Command Line

Download address for Kotlin command-line compiler:https://github.com/JetBrains/kotlin/releases/tag/v1.1.2-2The latest version is currently 1.1.2-2.

You can choose to download the latest stable version.

After the download is complete, unzip it to the specified directory, and then add the bin directory to the system environment variables. The bin directory contains scripts required for compiling and running Kotlin.

SDKMAN!

A simpler installation method can also be used on OS X, Linux, Cygwin, FreeBSD, and Solaris systems, with the following command:

$ curl -s https://get.sdkman.io | bash
$ sdk install kotlin

Homebrew

On OS X, you can use Homebrew to install:

$ brew update
$ brew install kotlin

MacPorts

If you are a MacPorts user, you can use the following command to install:

$ sudo port install kotlin

Create and run the first program

Create a file named hello.kt with the following code:

fun main(args: Array<String>) {
    println("Hello, World!")
}

Use the Kotlin compiler to compile the application:

$ kotlinc hello.kt -include-runtime -d hello.jar
  • -d: Used to set the name of the compiled output, which can be a class or .jar file, or a directory.

  • -include-runtime : The .jar file includes the Kotlin runtime library, so it can be run directly.

If you want to see all available options, run:

$ kotlinc -help

Running the application

$ java -jar hello.jar
Hello, World!

Compile to library

If you need to provide the generated jar package to other Kotlin programs without including the Kotlin runtime library:

$ kotlinc hello.kt -d hello.jar

Since the .jar file generated in this way does not contain the Kotlin runtime library, you should ensure that the runtime is on your classpath when it is used.

You can also use the kotlin command to run the .jar file generated by the Kotlin compiler

$ kotlin -classpath hello.jar HelloKt

HelloKt is the default class name generated by the compiler for the hello.kt file.

Running REPL (Interactive Interpreter)

We can run the following command to get an interactive shell, then input any valid Kotlin code and see the result immediately

Executing scripts using the command line

Kotlin can also be used as a scripting language with the file extension .kts.

For example, we create a file named list_folders.kts with the following code:

import java.io.File
val folders = File(args[0]).listFiles { file -> file.isDirectory()
folders?.forEach { folder -> println(folder)}

Execute through -Set the script options for the corresponding script file.

$ kotlinc -$ kotlinc script list_folders.kts <path_to_folder>

$ kotlinc -script list_folders.kts