Monday, October 28, 2019

Kotlin compiles with the command line

The Kotlin command line compilation tool download address: https://github.com/JetBrains/kotlin/releases/tag/v1.1.2-2, the latest is 1.1.2-2.
You can choose the latest stable version to download.
Once the download is complete, extract to the specified directory and add the bin directory to the system environment variable. The bin directory contains the scripts needed to compile and run Kotlin.
SDKMAN!
A simpler installation method is also available on OS X, Linux, Cygwin, FreeBSD, and Solaris systems. The commands are as follows:
$ curl -s https://get.sdkman.io | bash
$ sdk install kotlin
Homebrew
Under OS X, you can use Homebrew to install:
$ brew update
$ brew install kotlin
MacPorts
If you are a MacPorts user, you can install it with the following command:
$ sudo port install kotlin
Create and run the first program
Create a file called 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: The name used to set the compiled output, either a class or a .jar file, or a directory.
-include-runtime : Let the .jar file contain the Kotlin runtime so that it can run directly.
If you want to see all the available options, run:
$ kotlinc -help
Running the app
$ java -jar hello.jar
Hello, World!
Compile into a library
If you need to use the generated jar package for other Kotlin programs, you don't need to include Kotlin's runtime:
$ kotlinc hello.kt -d hello.jar
Since the .jar file generated like this does not contain the Kotlin runtime, you should make sure 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.
Run REPL (interactive interpreter)
We can run the following command to get an interactive shell, then enter any valid Kotlin code and see the result immediately.
Kotlin compiles with the command line

Execute scripts using the command line
Kotlin can also be used as a scripting language with a file extension of .kts.
For example, we create a file named list_folders.kts with the following code:
 Import java.io.File
Valball = File(args[0]).listFiles { file -> file.isDirectory() }
Folder?.forEach { folder -> println(folder) }
The corresponding script file is set by the -script option during execution.
$ kotlinc -script list_folders.kts <path_to_folder>

No comments:

Post a Comment