Kotlin DSL: defining and referencing variables in settings.gradle.kts

variables defined in the settings.gradle.kts cannot be referenced in the plugins block.

A stripped-down sample of by settings.gradle.kts:

val version1 = "1.2.3"
val version2 = "4.5.6"

pluginManagement {
   repositories {
   plugins {
      id("a.plugin.id") version version1

dependencyResolutionManagement {
   create("libs") {
      library("mylib", "org", "name").version(version2)

In the plugins block I get a reference error as the variable version1 is not found, whereas in the dependencyResolutionManagement block the variable version2 is correctly referenced.

If I move the definition of variable1 inside the plugins block then the settings script works OK.
The same happens if I define the versions in the gradle.properties file and reference them in the settings script like

val version1: String by settings

Again, if the val is defined (by delegation) at the top of the settings file then I get the reference error, while if I put the definition (by delegation) inside the plugins block, then things work OK.

Can someone explain to me what is going on here and if there is a way to obtain what one would consider a ‘normal’ behaviour in a script, i.e. that the variables defined at the outermost scope can be referenced in the inner blocks?

A final remark: I am on gradle 7.4 on Windows 10, kotlin 1.6.20-RC

Thanks a lot,

No you can’t.
The plugins block in build scripts and the pluginManagement block in settings scripts are special.
They are evaluated before the whole script separately.
In case of the plugins block in build scripts to generate the type-safe accessors up-front by applying the same plugins block to a dummy project and inspecting the effect.
In case of the pluginManagement block in settings scripts because it can have an includeBuild that contains settings plugins that can then be applied to the settings script.

But you could consider not using the pluginManagement { plugins { ... } } block to define your default version for that plugin and instead use the version catalog capability to define plugins with a version that you then can apply in your build scripts.