Kotlin compiles using the command line


Release date:2023-09-21 Update date:2023-10-13 Editor:admin View counts:393

Label:

Kotlin compiles using the command line

Kotlin download address of command line compilation tool: 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.

When the download is complete, extract it to the specified directory, and then set the bin directory is added to the system environment variable.``bin`` directory contains compiling and running Kotlin required script.

SDKMAN!

A simpler installation method is also available on OS X, Linux, Cygwin, FreeBSD, and Solaris systems with the following commands:

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

$ sdk install kotlin

Homebrew

Under OS X, you can use the Homebrew installation:

$ brew update
$ brew install kotlin

MacPorts

If you are MacPorts for users, you can install using the following command:

$ sudo port install kotlin

Create and run the first program

Create a file named hello.kt file, the code is as follows:

hello.kt

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

Use Kotlin compiler compiles applications:

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

  • -include-runtime let .jar file contains Kotlin run the library so that you can run it directly.

If you want to see all the options available, run:

$ kotlinc -help

Run the application

$ java -jar hello.jar
Hello, World!

Compile into a library

If you need to add the generated jar package for others Kotlin , theprogram is used, but it does not need to include Kotlin runtime of:

$ kotlinc hello.kt -d hello.jar

Because of the generated in this way .jar file does not contain Kotlin runtime, so you should make sure that when it is used, the runtime is in your classpath .

You can also use it. kotlin command to run Kotlin generated by thecompiler .jar file

$ kotlin -classpath hello.jar HelloKt

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

Run REPL (interactive interpreter)

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

Image0

Use the command line to execute the script

Kotlin can also be used as a scripting language with a file suffix named .kts .

For example, we create a file named list_folders.kts code is as follows:

import java.io.File

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

Pass at execution time -script option to set the appropriate script file.

$ kotlinc -script list_folders.kts <path_to_folder>

$ kotlinc -script list_folders.kts

Powered by TorCMS (https://github.com/bukun/TorCMS).