
Gradle プロジェクトの準備
init タスクでプロジェクト準備します(gradle は導入済みの前提)。
$ mkdir kotlin-example $ cd kotlin-example $ gradle init
kotlin-gradle-plugin を使うよう build.gradle を編集します。
plugins {
id "org.jetbrains.kotlin.jvm" version "1.1.3-2"
}
apply plugin: 'application'
mainClassName = 'code.example.HelloWorldKt'
repositories {
jcenter()
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jre8"
}
依存にはkotlinの標準ライブラリを指定します。JDK8 用に kotlin-stdlib-jre8 を使っています。
application プラグインで実行するメインクラスは末尾にKt が付与されたクラスとして指定します。

ソースファイルの作成
パッケージとソースファイル作成します。
$ mkdir -p src/main/kotlin/code/example $ touch src/main/kotlin/code/example/HelloWorld.kt
HelloWorld.kt を以下のように編集します。
package code.example fun main(args: Array<String>) { println("Hello World!!") }
ビルド&実行
ビルドします
$ ./gradlew build $ ./gradlew
実行
$ ./gradlew run > Task :run Hello World!!
以上最低限のサンプルでした。
ここからは番外編。
ビルドスクリプトをKotlinで書く
Gradle では、kotlin-dsl(https://github.com/gradle/kotlin-dsl) により、ビルドスクリプトを Kotlin で書くことができます。
現在の Gradle 4.0.2 では、前述の build.gradle を build.gradle.kts (Kotlin Script) にリネームして、以下のように変更してビルドできます。
plugins {
application
}
configure<ApplicationPluginConvention> {
mainClassName = "code.example.HelloWorldKt"
}
configure<JavaPluginConvention> {
setSourceCompatibility(1.8)
setTargetCompatibility(1.8)
}
repositories {
jcenter()
}
dependencies {
compile(kotlinModule("stdlib"))
}
以前(kotlin-dsl v0.8.0)は settings.gradle に、以下のようにビルドファイル名を指定する必要がありました。
rootProject.buildFileName = 'build.gradle.kts'
しかし現在は、build.gradle を build.gradle.kts に変更するだけで動きます(Gradle 4.0.2 に含まれる kotlin-dsl のバージョンが若干さだかではないですが、多分 kotlin-dsl v0.8.0 〜 v0.9.0 あたりな気がします)。
2017年5月あたりでは、build.gradle.kts は以下のように書く必要がありました。
apply<ApplicationPlugin>()
configure<ApplicationPluginConvention> {
mainClassName = "samples.HelloWorld"
}
configure<JavaPluginConvention> {
setSourceCompatibility(1.7)
setTargetCompatibility(1.7)
}
repositories {
jcenter()
}
dependencies {
testCompile("junit:junit:4.12")
}
そして、Gradle 4.1 向けに現在絶賛開発中の kotlin-dsl では、以下のように書くことができる模様です。
plugins {
application
}
application {
mainClassName = "samples.HelloWorld"
}
java {
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
}
dependencies {
testCompile("junit:junit:4.12")
}
repositories {
jcenter()
}
ここまで来ると、もはやこれが Kotlin のコードなんて、、見分けがつきませんね。