Kotlin 1.1-RCがでたので、試したい!

2017.02.20

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

まえがき

Kotlin 1.1 Release Candidate is Here | Kotlin Blog

魅了的な機能がたくさん。一歩先取りで、1.1を試してみよう。方法先程のページ書いてあるのですが、ちょっとわかりずらかったので、インストール仕方を説明します。

How to try it

In Maven/Gradle: Add http://dl.bintray.com/kotlin/kotlin-eap-1.1 as a repository for the build script and your projects; use 1.1.0-rc-91 as the version number for the compiler and the standard library.

In IntelliJ IDEA: Go to Tools → Kotlin → Configure Kotlin Plugin Updates, then select “Early Access Preview 1.1” in the Update channel drop-down list, then press Check for updates.

Kotlin 1.1 Release Candidate is Here より

インストール仕方

念のため、まっさら状態から説明します。

Android StudioにKotlin Pluginをインストール

[Android Studio] -> [Preferences] -> [Plugin] -> [install JetBrains plugin...] -> -> [Android Studio 再起動]

KotlinのRCのPluginをインストールする

スクリーンショット_2017-02-20_18_06_22

Stable版しか取得できないのでRC版のPluginを入れるようにする スクリーンショット_2017-02-20_18_10_01

スクリーンショット_2017-02-20_18_10_17

Build.gradleでKotlinを追加

直接追加してもよいですが、Android Studioがやってくれます。

スクリーンショット_2017-02-20_18_11_17

スクリーンショット_2017-02-20_18_11_23

RCは直接入らないので、 1.0.6で設定します。

スクリーンショット_2017-02-20_18_11_29

Build.gradleでRCを読むようにする

/build.gradleにRCのリポジトリの追加とRCのバージョンに変更します。

buildscript {
-    ext.kotlin_version = '1.0.6'
+    ext.kotlin_version = '1.1.0-rc-91'
    repositories {
        jcenter()
+       maven { url 'http://dl.bintray.com/kotlin/kotlin-eap-1.1' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
+       maven { url 'http://dl.bintray.com/kotlin/kotlin-eap-1.1' }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

これでビルドすれば動くはずです。

ビルドエラーになってしまう場合

Android Studioでbuild.gradleの設定をした場合、Java8版のKotlinが追加されてしまい、エラーになる場合があります。

app/build.gradleを確認しましょう。

Error:Error converting bytecode to dex:
Cause: Dex cannot parse version 52 byte code.
This is caused by library dependencies that have been compiled using Java 8 or above.
If you are using the 'java' gradle plugin in a library submodule add 
targetCompatibility = '1.7'
sourceCompatibility = '1.7'
to that submodule's build.gradle file.
compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"

Java8版をやめる

- compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
+ compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"

Java8版に対応する

以下の部分を、追加しました。

android {

    defaultConfig {
        ...

        jackOptions {
            enabled true
        }
    }

    ...

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

まとめ

RCまでくれば、正式版までもうすぐ!?

Kotlin 1.1の魅力的な機能をどんどんつかっていきましょう。