My Favorite Things - Coding or die.

とある技術者の経験記録、的な。

Kotlin で HelloWorld(コマンドライン編)

さて前回に続いて、今度はコマンドラインで Kotlin のHelloWorldをやってみたいと思います。

公式ドキュメントのチュートリアルを見ながら進めていきます.

インストー

まずは念のため既にインストールされていないか確認します。

$ kotlinc
zsh: command not found: kotlinc

IntelliJ IDEA で自動でインストールされてはいないようですね。

SDKMAN! のインストー

brewでインストールするのが手っ取り早いかと思ったのですが、 SDKMAN!という複数バージョンを共存させられるrbenvと似たようなツールがあるようです。

しかもKotlin以外の言語にも対応しているとのことで今後も使えそうなので、これを使ってインストールしてみます。

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


Please open a new terminal, or run the following in the existing one:

    source "/Users/yusuke/.sdkman/bin/sdkman-init.sh"

Then issue the following command:

    sdk help

Enjoy!!!

以下のコマンドを実行して有効にします。

$ source "/Users/yusuke/.sdkman/bin/sdkman-init.sh"

sdk helpと試しに打ってみると。

$ sdk help

Usage: sdk <command> [candidate] [version]
       sdk offline <enable|disable>

   commands:
       install   or i    <candidate> [version]
       uninstall or rm   <candidate> <version>
       list      or ls   [candidate]
       use       or u    <candidate> [version]
       default   or d    <candidate> [version]
       current   or c    [candidate]
       upgrade   or ug   [candidate]
       version   or v
       broadcast or b
       help      or h
       offline           [enable|disable]
       selfupdate        [force]
       flush             <candidates|broadcast|archives|temp>

   candidate  :  the SDK to install: groovy, scala, grails, gradle, kotlin, etc.
                 use list command for comprehensive list of candidates
                 eg: $ sdk list

   version    :  where optional, defaults to latest stable if not provided
                 eg: $ sdk install groovy

sdk listというコマンドを使うとインストール可能なツールや言語の一覧が表示できるっぽいです。

================================================================================
Available Candidates
================================================================================
q-quit                                  /-search down
j-down                                  ?-search up
k-up                                    h-help

--------------------------------------------------------------------------------
Activator (1.3.10)                   http://www.lightbend.com/activator/download

Typesafe is a GUI/CLI tool to help with building reactive applicaions. It uses
sbt (simple build tool) behind the scenes to build, run, and test your project.
It provides a code editing interface, and provides templaes and seeds for you to
clone and use.

                                                         $ sdk install activator
--------------------------------------------------------------------------------
Ant (1.10.1)                                             https://ant.apache.org/

...

Kotlin のインストー

SDKMAN!を使ってインストールをします。

sdk list kotlinコマンドで、一応インストール可能なバージョン一覧を見てみます。

$ sdk list kotlin

================================================================================
Available Kotlin Versions
================================================================================
     1.1.2-2              1.0.3                                                    
     1.1.2                1.0.2                                                    
     1.1.1                1.0.1-2                                                  
     1.1-beta2            1.0.1-1                                                  
     1.1-beta             1.0.1                                                    
     1.1-RC               1.0.0                                                    
     1.1-M04                                                                       
     1.1-M02                                                                       
     1.1-M01                                                                       
     1.1                                                                           
     1.0.7                                                                         
     1.0.6                                                                         
     1.0.5-2                                                                       
     1.0.5                                                                         
     1.0.4                                                                         

================================================================================
+ - local version
* - installed
> - currently in use
================================================================================

なるほど今日時点の最新は1.1.2-2なのですね。

sdk install kotlinで最新版をインストールします。

$ sdk install kotlin

Downloading: kotlin 1.1.2-2

In progress...

######################################################################## 100.0%

Installing: kotlin 1.1.2-2
Done installing!


Setting kotlin 1.1.2-2 as default.

もう一度sdk list kotlinしてみる、最新版がインストールされて有効になっているのが分かります。

$ sdk list kotlin

================================================================================
Available Kotlin Versions
================================================================================
 > * 1.1.2-2              1.0.3                                                    
     1.1.2                1.0.2                                                    
     1.1.1                1.0.1-2                                                  
     1.1-beta2            1.0.1-1                                                  
     1.1-beta             1.0.1                                                    
     1.1-RC               1.0.0                                                    
     1.1-M04                                                                       
     1.1-M02                                                                       
     1.1-M01                                                                       
     1.1                                                                           
     1.0.7                                                                         
     1.0.6                                                                         
     1.0.5-2                                                                       
     1.0.5                                                                         
     1.0.4                                                                         

================================================================================
+ - local version
* - installed
> - currently in use
================================================================================

下の方に書いてありますが、

  • * がインストール済み
  • > が現在有効になっているバージョン

ということみたいですね。

+はまだ表示されていないので断言できませんが、特定のディレクトリに適用されたバージョンが表示されるのでしょう。

Hello, world!

ソース作成

さてまずはhello.ktを作成します。

$ touch hello.kt
$ vim hello.kt
fun main(args: Array<String>) {
    println("Hello, World!")
}

コンパイル

つぎはコンパイルですね。

kotlincというコマンドを使ってコンパイルするようです。 (ちょっと長いのでktcとかエイリアスを貼ってもいいかもですね)

$ kotlinc hello.kt -include-runtime -d hello.jar

-dが出力を指定するもの、-include-runtime.jarの中にKotlinのランタイムを同梱するオプションのようです。

ちなみに最初に拡張子を.ktではなく.tkとしてしまっていたのですが、そうした場合は以下のようなエラーが出てコンパイルできませんでした。

$ kotlinc hello.tk -include-runtime -d hello.jar
error: source entry is not a Kotlin file: hello.tk

なるほど拡張子は.ktでないとKotlinのソースとしては認識されないのですね。

実行

さてディレクトリの中身を見ると、hello.jarがちゃんと出来ていますね。

$ ls
hello.jar  hello.kt

javaコマンドを使ってjava -jar hello.jarで実行できるようです。

$ java -jar hello.jar 
Hello, World!

ちゃんと実行できましたね。

kotlinc

kotlinc -helpでヘルプが見られるようなので確認しておきます。

$ kotlinc -help
Usage: kotlinc-jvm <options> <source files>
where possible options include:
  -d <directory|jar>         Destination for generated class files
  -classpath (-cp) <path>    Paths where to find user class files
  -include-runtime           Include Kotlin runtime in to resulting .jar
  -jdk-home <path>           Path to JDK home directory to include into classpath, if differs from default JAVA_HOME
  -no-jdk                    Don't include Java runtime into classpath
  -no-stdlib                 Don't include Kotlin runtime into classpath
  -no-reflect                Don't include Kotlin reflection implementation into classpath
  -module <path>             Path to the module file to compile
  -script                    Evaluate the script file
  -script-templates <fully qualified class name[,]>
                             Script definition template classes
  -kotlin-home <path>        Path to Kotlin compiler home directory, used for runtime libraries discovery
  -module-name               Module name
  -jvm-target <version>      Target version of the generated JVM bytecode (1.6 or 1.8), default is 1.6
  -java-parameters           Generate metadata for Java 1.8 reflection on method parameters
  -language-version <version> Provide source compatibility with specified language version
  -api-version <version>     Allow to use declarations only from the specified version of bundled libraries
  -nowarn                    Generate no warnings
  -verbose                   Enable verbose logging output
  -version                   Display compiler version
  -help (-h)                 Print a synopsis of standard options
  -X                         Print a synopsis of advanced options
  -P plugin:<pluginId>:<optionName>=<value>
                             Pass an option to a plugin

もっと大量のオプションを予想していたのですが、思ったよりは少ないですね。(swiftc --helpの量が多すぎるのかも分かりませんが)

今後必要な時に見ていくことにします。

最後に

さて無事にコマンドラインでKotlinのHelloWorldを試すことが出来ました。 最近の言語は試すのが導入から試すまでが簡単で良いですね。

ちなみにチュートリアルのページには、ライブラリの作成方法やREPL、スクリプトとしての実行などが含まれているのですが、続きは別の記事にしたいと思います。