Kotlin DSL - defining a constant that can be used inside init functions

I'm using Kotlin DSL, and I'd like to define a constant that I use in several places, including in anonymous functions passed in as the `init` paramter to various TeamCity classes.  But if I have a `settings.kts` like this:

import jetbrains.buildServer.configs.kotlin.v2019_2.*
version = "2021.2"
val MY_CONST = "1234"
class MyBuildType : BuildType({
name = MY_CONST
})
project {}

This generates this error:

[ERROR] Error while generating TeamCity configs:
[ERROR] Compilation error: org.jetbrains.kotlin.backend.common.BackendException: Backend Internal error: Exception during IR lowering

...followed by a huge spew of stuff.

After searching online (and a lot of tedious bisecting to first figure out that the issue was the constant), it seems that you can't refer to a global level variable inside of functions that are going to be executed in other contexts.  I found this article, which suggests just prefacing the variable name with the "package name" - but since this is a .kts script file, I don't know what that package name is.

So what is that package name? Or, more generally, how does one define constants in kotlin scripts?

0
1 comment

As a workaround, I found that you can use an anonymous object declaration as a namespace:

import jetbrains.buildServer.configs.kotlin.v2019_2.*
version = "2021.2"
object Constants {
val MY_CONST = "1234"
}
class MyBuildType : BuildType({
name = Constants.MY_CONST
})
project {}
1

Please sign in to leave a comment.