Monday, April 13, 2020

Kotlin Compile Kotlin using command line

Kotlin command line compilation tool download address: https://github.com/JetBrains/kotlin/releases/tag/v1.1.2-2 , currently the latest is 1.1.2-2.
You can choose a latest stable version to download.
After the download is complete, unzip to the 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!
The simpler installation method can also be used on OS X, Linux, Cygwin, FreeBSD and Solaris systems. The command is 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 use the following command to install:
$ sudo port install kotlin
Create and run the first program
Create a file named hello.kt, the code is as follows:
hello.kt
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 compilation output, which can be a class or .jar file, or a directory.
-include-runtime : Let the .jar file include the Kotlin runtime library so that it can be run directly.
If you want to see all the available options, run:
$ kotlinc - help
Run the application
$ java -jar hello.jar
Hello, World!
Compile to library
If you need to use the generated jar package for other Kotlin programs, you do not need to include the Kotlin runtime library:
$ kotlinc hello . kt - d hello . canyon
Since the .jar file generated in this way does not contain the Kotlin tutorial runtime library, you should make sure that when it is used, it is on your classpath at runtime.
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).
Kotlin Compile Kotlin using command line

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

Setup Kotlin for Android Studio

Execute script using command line
Kotlin can also be used as a scripting language with a file extension of .kts.

For example, we create a list_folders.kts, the code is as follows:
import java . io . File
val folders = File(args[0]).listFiles { file -> file.isDirectory() }
folders?.forEach { folder -> println(folder) }
Set the corresponding script file through the -script option during execution.
$ kotlinc -script list_folders.kts <path_to_folder>
$ kotlinc -script list_folders.kts
Tags: Kotlin Compile Kotlin using command line,Install, compile and run Kotlin from command line,Working with the Command Line Compiler - Kotlin,Using the command line to compile and run Kotlin code 

2 comments: