LoginSignup
8
8

More than 5 years have passed since last update.

KotlinとJavaが混在するプロジェクトにおけるGradleのCompile Encoding設定について

Posted at

確認環境

  • Gradle v3.0
  • Java v1.8.0_102
  • Kotlin v1.0.4

経緯

Javaで作られたプロジェクトにKotlinを混ぜ込んでbuildした際にGradleがエラーを吐いたために気がつきました。

元ソース

build.gradle(抜粋)
apply plugin: 'java'

def defaultEncoding = 'UTF-8'
tasks.withType(AbstractCompile).each {
    it.options.encoding = defaultEncoding
}

Kotlin追加後(エラー発生)

build.gradle(抜粋)
buildscript {
    // 省略
}

apply plugin: 'java'
apply plugin: 'kotlin'

def defaultEncoding = 'UTF-8'
tasks.withType(AbstractCompile).each {
    it.options.encoding = defaultEncoding
}

この状態でgradle checkを実行すると以下のエラーが発生します。

build.gradleエラー内容
FAILURE: Build failed with an exception.
* Where:
Build file 'build.gradle' line: 24
* What went wrong:
A problem occurred evaluating root project 'fooProject'.
> Could not get unknown property 'options' for task ':compileKotlin' of type org.jetbrains.kotlin.gradle.tasks.KotlinCompile.

どうやらorg.jetbrains.kotlin.gradle.tasks.KotlinCompileがoptionsを持っていないことが原因の模様。
(同様にKotlinTestCompileもoptionsを持っていませんでした)

解決策

ふつうに使うものを列挙すればいいよね、ということで解決しました。

build.gradle(最終版)
buildscript {
    // 省略
}

apply plugin: 'java'
apply plugin: 'kotlin'

def defaultEncoding = 'UTF-8'
[compileJava, compileTestJava]*.options*.encoding = defaultEncoding

一瞬Kotlinを除外するか・・・とか考えたのですが、どうみてもネタ。。。

build.gradle(ネタ)
tasks.withType(AbstractCompile)
     .matching({t -> !t.getName().contains("Kotlin")})
     .each {
         it.options.encoding = defaultEncoding
     }
8
8
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
8
8