LoginSignup
1
0

More than 3 years have passed since last update.

Gradle Kotlin DSLでversions.gradleのように依存ライブラリのバージョンを記述する

Posted at

Gradleのマルチモジュールで構成されるプロジェクトの依存ライブラリのバージョン定義について。

従来のGroovy DSLだとversions.gradleのようなファイルに依存ライブラリのバージョンを記述して、各モジュールのbuild.gradleから参照することで、モジュールで使用している依存ライブラリのバージョンを統一できた。

Kotlin DSLでは、versions.gradleを定義する方法は使えない模様。ただし、別のやり方があるので、それを述べる。ファイルパスは、プロジェクトのルートフォルダ起点で示す。

Step 1. 「buildSrc/build.gradle.kts」を作る

内容は以下のようにする。

build.gradle.kts
plugins {
    `kotlin-dsl`
}

repositories {
    jcenter()
}

Step 2. 「buildSrc/src/main/java/Versions.kt」を作成する

Versions.kt
object Versions {
    const val kotlin = "1.4.20"
    const val appcompat = "1.2.0"
}

やりたければ、objectを入れ子にしたりしてライブラリのグルーピングもできる。普通のkotlinファイルなので。

Step 3. 「build.gradle.kts」から参照する

後は、Step 2で定義した定数を参照すればよいだけ。以下、参照例。

build.gradle.kts
buildscript {
    repositories {
        ...
    }
    dependencies {
        ...
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${Versions.kotlin}")
    }
}
module/build.gradle.kts
...

dependencies {
    implementation("org.jetbrains.kotlin:kotlin-stdlib:${Versions.kotlin}")
    implementation("androidx.appcompat:appcompat:${Versions.appcompat}")
    ...
}

注意事項

verisons.gradleだと、依存ライブラリに新しいバージョンがあれば警告が出るが、この方法だと出ない

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