Kotlin Command Line Compilation
Download link for Kotlin command line compilation tool: https://github.com/JetBrains/kotlin/releases/tag/v1.1.2-2, the latest version is currently 1.1.2-2.
You can choose to download the latest stable version.
After downloading, extract to a specified directory, and then add the bin
directory to the system environment variables. The bin
directory contains the scripts needed to compile and run Kotlin.
SDKMAN!
A simpler installation method can also be used on OS X, Linux, Cygwin, FreeBSD, and Solaris systems, with the following commands:
$ curl -s https://get.sdkman.io | bash
$ sdk install kotlin
Homebrew
On OS X, you can install with Homebrew:
$ brew update
$ brew install kotlin
MacPorts
If you are a MacPorts user, you can install with the following command:
$ sudo port install kotlin
Creating and Running Your First Program
Create a file named hello.kt with the following code:
hello.kt
fun main(args: Array<String>) {
println("Hello, World!")
}
Compile the application with the Kotlin compiler:
$ kotlinc hello.kt -include-runtime -d hello.jar
--d : Sets the name of the compilation output, which can be a class or a .jar file, or a directory.
--include-runtime : Makes the .jar file include the Kotlin runtime library, allowing it to be run directly.
If you want to see all available options, run:
$ kotlinc -help
Run the application
$ java -jar hello.jar
Hello, World!
Compiling into a Library
If you need to generate a jar package for use by other Kotlin programs, you can omit the inclusion of the Kotlin runtime library:
$ kotlinc hello.kt -d hello.jar
Since the .jar file generated in this way does not include 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 the REPL (Interactive Interpreter)
We can run the following command to get an interactive shell, then enter any valid Kotlin code and immediately see the results.
Executing Scripts from the Command Line
Kotlin can also be used as a scripting language, with the file extension .kts.
For example, 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) }
When executing, set the corresponding script file with the -script option.
$ kotlinc -script list_folders.kts <path_to_folder>