Kotlin Command Line
# Kotlin Command-Line Compilation
Kotlin command-line compilation tool download address: [https://github.com/JetBrains/kotlin/releases/tag/v1.1.2-2](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 it 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!
On OS X, Linux, Cygwin, FreeBSD, and Solaris systems, you can also use a simpler installation method with the following command:
$ curl -s https://get.sdkman.io | bash $ sdk install kotlin
### Homebrew
On OS X, you can install using Homebrew:
$ brew update $ brew install kotlin
### MacPorts
If you are a MacPorts user, you can install using the following command:
$ sudo port install kotlin
* * *
## Creating and Running the First Program
Create a file named `hello.kt` with the following code:
## hello.kt
fun main(args: Array){println("Hello, World!")}
Compile the application using the Kotlin compiler:
$ kotlinc hello.kt -include-runtime -d hello.jar
* **-d**: Used to set the name of the compiled output, which can be a class file, 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 to a Library
If you need the generated jar package to be used by other Kotlin programs, you can omit the Kotlin runtime library:
$ kotlinc hello.kt -d hello.jar
Since the generated .jar file 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 .jar files 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 see the results immediately.
!(#)
* * *
## Executing Scripts from 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).listFiles { file -> file.isDirectory() } folders?.forEach { folder -> println(folder) }
When executing, use the `-script` option to specify the corresponding script file.
$ kotlinc -script list_folders.kts $ kotlinc -script list_folders.kts
YouTip