Leo Aso
Leo Aso

Reputation: 12513

Why must $kotlin_version be explicitly specified in Android?

Supporting Kotlin in an Android studio project requires two dependencies: kotlin-gradle-plugin in Project/build.gradle and kotlin-stdlib-jdk7 in Project/app/build.gradle, and these two need to have the same version. The common method seems to be using a single kotlin_version variable which you then have to manually change when the IDE updates its Kotlin plugin — as of Android Studio 3.1.3, the IDE is still not able to automatically update the dependencies if you use a $variable as the version.

implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

In non-Android Kotlin projects i.e. those using apply: 'kotlin' instead of apply plugin: 'kotlin-android', it is possible to simply omit the version from the kotlin-stdlib-jdk7 dependency, which will then be automatically resolved from the plugin.

implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk7'

This even works on non-Android modules within Android projects. My question is, why is this not possible in Android modules? Why can't the $kotlin_version simply be omitted? If the feature has been present since Kotlin 1.1.2, why is it still causing compile errors on Android even on Kotlin 1.2.51? Or is it actually possible to do this, and if so, how can it be done?

Upvotes: 5

Views: 3452

Answers (1)

Alexander Egger
Alexander Egger

Reputation: 5300

In fact this is not Kotlin specific but has to do with how Gradle manages dependencies.

See https://docs.gradle.org/current/userguide/declaring_dependencies.html on how to specify the version of a dependency in Gradle.

In this case

implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

is the standard way of setting the version. As the this version number is the same for several dependency it is declared in a variable in order to make it easy to change the version for all Kotlin libraries.

implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk7'

Uses dependency constraints which are available since Gradle 4.6. It is used for the same purpose. One can set the version of a library in a central place and this way keep the version at a common value without having to go through all gradle.properties files of a larger project.

Upvotes: 0

Related Questions