LoginSignup
6
11

More than 5 years have passed since last update.

Kotlin CLI の使い方: kotlin, kotlinc, kotlinc-js, kotlin-dce-js

Last updated at Posted at 2018-06-10

Kotlin 1.2.41 を前提に、 Kotlin CLI の使い方をまとめました。

スクリプトを実行する場合

拡張子 kts のファイルを作って実行します。 拡張子が kts でない場合は、中身の如何にかかわらず実行してくれません (error: source entry is not a Kotlin file とエラーが出ます)。

kotlinc -script sample.kts

このとき、 sample.ktsmain がなくても実行できます。

コード例

sample.kts
println("Hello World!")

ファイルをコンパイルする

JVM コンパイル

kotlinc Sample.kt

この場合、 SampleKt.class が生成されます。

kotlinc Sample.kt -include-runtime -d Sample.jar

このようにすると JAR が作成されます。 出力された Sample.jar を次のようにして実行します。

kotlin Sample.jar

または

java -jar Sample.jar

JS コンパイル

kotlinc-js Sample.kt -output sample.js

javascript ファイル sample.js が出力されます。 map, meta はオプションを付けることで出力可能です。

Kotlin DCE JS

DCE とは dead code elimination のことで、 使われていないコードは javascript のファイルをでっかくするだけなので消しましょうというものです。 (参考: https://kotlinlang.org/docs/reference/javascript-dce.html)

例えば次のように Hello.kt を作成します。

Hello.kt
fun main(vararg args: String) {
    println("Kotlin")
}

fun a() {
    println(1)
}

見ての通り 関数 a は使われていません。 これを次のように JS Compile をします。

kotlinc-js Hello.kt -output hello.js

すると次のような hello.js が作成されます。

hello.js
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(9);
  }
  _.main_vqirvp$ = main;
  _.a = a;
  main([]);
  Kotlin.defineModule('hello', _);
  return _;
}(typeof hello === 'undefined' ? {} : hello, kotlin);

ここで kotlin-dce-js を実行します。

kotlin-dce-js hello.js

オプション -d で出力ディレクトリを指定できますが、ここでは指定していません。 デフォルトの min ディレクトリに次の hello.js が出力されます。

hello.js
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

使用されていなかった 関数 a は除去されています。

REPL (Read Eval Print Loop)

次のコマンドで、 REPL が実行できます。

kotlinc

:quit を入力することで終了できます。 私はよく Ctrl+D で終了しています。
そのほかに、次のコマンドが使用できます。

  • :help : ヘルプを表示
  • :dump bytecode : クラスのバイトコードをターミナルに出力するそうです。 使い方がよくわかっていません。
  • :load <file> : スクリプトを読み込みます。

その他

kotlin, kotlinc, kotlinc-js, kotlin-dce-js のコマンドを紹介しました。 各コマンドに -h オプション を付けて実行するとそれぞれのコマンドのヘルプが表示されます。

6
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
11