LoginSignup
1
1

More than 5 years have passed since last update.

ことりんと一緒 - 6. Kotlin/Native

Posted at

概要 / 説明

Kotlin 1.3 のリリースには、ベータ版となった Kotlin/Native が含まれています。
簡単に IntelliJ から Kotlin/Native を使ってみたいと思います。

Kotlin/Native

Kotlin は Java や Scala 同様に JVM 言語として設計されています。そのため、実行するには 仮想マシン(JVM) が必要となります。ところが、この Kotolin/Native は 仮想マシンを必要せずに動作するように ネイティブバイナリとしてコンパイルする技術です。

前提 / 環境

ランタイムバージョン

  • Kotlin : 1.3.0

開発環境

  • OS : Mac
  • IDE : IntelliJ IDEA
  • Build : Gradle

手順 / 解説

1. Kotlin/Native プロジェクトの作成

image.png

新規プロジェクトを作成する時に選択するプロジェクトタイプとして、Kotlin カテゴリの中に含まれている、Kotlin/Native を選択します。
プロジェクトの構成はデフォルトのままで問題なしです。

2. プロジェクト構成

image.png

ソースコードディレクトリが自動で作られています。環境の OS が MacOS だからか、ディレクトリ名が macosMain となっています。

3. ソースコード

build.gradle

plugins {
    id 'kotlin-multiplatform' version '1.3.0'
}
repositories {
    mavenCentral()
}
kotlin {
    targets {
        fromPreset(presets.macosX64, 'macos')

        configure([macos]) {
            compilations.main.outputKinds('EXECUTABLE')
            compilations.main.entryPoint = 'sample.main'
        }
    }
    sourceSets {
        macosMain {
        }
        macosTest {
        }
    }
}

task runProgram {
    def buildType = 'release'
    dependsOn "link${buildType.capitalize()}ExecutableMacos"
    doLast {
        def programFile = kotlin.targets.macos.compilations.main.getBinary('EXECUTABLE', buildType)
        exec {
            executable programFile
            args ''
        }
    }
}

アプリケーション

package sample

fun hello(): String = "Hello, Kotlin/Native!\n"

fun main(args: Array<String>) {
    println(hello())
    platform.posix.system("date")
    platform.posix.system("ls -la")
}

基本に忠実に HelloWorld の標準出力と、外部コマンドの実行を入れてみました。

4. ビルド

image.png

Gradle タスクの build を実行します。

image.png

ネイティブバイナリを生成するためか、少し時間がかかるようです。

5. 実行

build/bin/macos/main/release/executable ディレクトリの配下にネイティブバイナリが生成されます。
このバイナリファイルは、MacOS上で直接どこでも実行できます。

build/bin/macos/main/release/executable $ ./HelloKotlinNative.kexe
Hello, Kotlin/Native!

2018年 11月18日 日曜日 21時01分51秒 JST
total 1984
drwxr-xr-x  3 shinyay  staff       96 11 18 20:36 .
drwxr-xr-x  3 shinyay  staff       96 11 18 20:35 ..
-rwxr-xr-x  1 shinyay  staff  1013336 11 18 20:36 HelloKotlinNative.kexe

まとめ / 振り返り

Kotlin/Native は、まだベータ版の扱いですが十分に楽しめそうです。
今回は外部コマンドの呼び出しとしてお試しに作ってみましたが、次はコマンドラインツールを作ってみようかなと思います。

今回のソース

1
1
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
1
1