Table of Contents
I write how to use Kotlin CLI, in Kotlin 1.2.41.
Execute Script
Execute script file with kts
extension. If the extension is not kts
, the command doesn’t execute anything. The error error: source entry is not a Kotlin file
is shown.
1 |
kotlinc -script sample.kts |
sample.kts
can be executed if it has no main
function.
Sample Code
1 |
println("Hello World!") |
Compile the File
JVM Compilationル
The following command compiles the Kotlin file with extension kt
and generates .class
file.
1 |
kotlinc Sample.kt |
SampleKt.class
will be created.
The following command creates JAR file.
1 |
kotlinc Sample.kt -include-runtime -d Sample.jar |
There are 2 ways to execute output Sample.jar
file, as follows.
1 |
kotlinc Sample.jar |
1 |
java -jar Sample.jar |
JS Compilation
The following command generates the JavaScript file, sample.js
. Map file and meta file are output if you add options.
1 |
kotlinc-js Sample.kt -output sample.js |
Kotlin DCE JS
DCE means dead code elimination. It eliminate unused codes in JavaScript. (Reference: https://kotlinlang.org/docs/reference/javascript-dce.html)
For example, create Hello.kt
as follows, which has an unused function a
.
1 2 3 4 5 6 7 |
fun main(vararg args: String) { println("Kotlin") } fun a() { println(1) } |
Compile it as follows.
1 |
kotlinc-js Hello.kt -output hello.js |
Then, hello.js
will be output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
if (typeof kotlin === 'undefined') { throw new Error("Error loading module 'hello'. Its dependency 'kotlin' was not found. Please, check whether 'kotlin' is loaded prior to 'hello'."); } var hello = function (_, Kotlin) { 'use strict'; var println = Kotlin.kotlin.io.println_s8jyv4$; function main(args) { println('Kotlin'); } function a() { println(1); } _.main_vqirvp$ = main; _.a = a; main([]); Kotlin.defineModule('hello', _); return _; }(typeof hello === 'undefined' ? {} : hello, kotlin); |
Then, execute kotlin-dce-js
as follows.
1 |
kotlin-dce-js hello.js |
You can use -d
option to designate the output directory. Here I don’t use it. Without the option, it outputs hello.js
into min
directory.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
if (typeof kotlin === 'undefined') { throw new Error("Error loading module 'hello'. Its dependency 'kotlin' was not found. Please, check whether 'kotlin' is loaded prior to 'hello'."); } var hello = function (_, Kotlin) { 'use strict'; var println = Kotlin.kotlin.io.println_s8jyv4$; function main(args) { println('Kotlin'); } _.main_vqirvp$ = main; main([]); return _; }(typeof hello === 'undefined' ? {} : hello, kotlin); //# sourceMappingURL=hello.js.map |
The unused function a
is successfully deleted.
REPL (Read Eval Print Loop)
We can execute REPL as follows.
1 |
kotlinc |
To exit the REPL, enter :quit
or Ctrl+D.
Help
Execute kotlin
, kotlinc
, kotlinc-js
, kotlin-dce-js
commands with the option -h
, you can see the help of each command.