Java – Assigning static final values from companion objects is not allowed in comments

Assigning static final values from companion objects is not allowed in comments… here is a solution to the problem.

Assigning static final values from companion objects is not allowed in comments

I created a class in Kotlin:

class Extras {
    companion object {
        var EXTRA_NAME: String? = null

fun setExtraName() {
           var extraName: String? = null
           //...
           EXTRA_NAME = extraName
        }
    }
}

I call setExtraName() in onCreate() of the Application class.

Then pass the EXTRA_NAME to the annotation of the method (defined in Java):

static final String EXTRA_NAME = Extras.Companion.getEXTRA_NAME();

@Extra(EXTRA_NAME)
void doSomething() {
}

However, I get the following error:

Attribute value must be constant

Why?

Solution

Solve this problem

Compilation succeeded

annotation class Test(
    val value: String
)

object Keys {
    const val API_KEY = "AB"
}

@Test(Keys.API_KEY)
fun doSomething() {

}

const makes the value compile-time constant, which allows it to be swapped into comments.

Why is this needed

Since annotation processors have access to annotations before runtime, they must be compile-time constants, which is why they must be defined using const in Kotlin.

Related Problems and Solutions