'kotlin const val Const 'val' are only allowed on top level or in objects

In my Kotlin project I want to declare constant on compile time:

So I use this:

@RunWith(AndroidJUnit4::class)
class TradersActivityTest {

    private lateinit var mockServer: MockWebServer
    private const val ONE_TR = "no_wallets.json" // error here

But I has compile time error:

Const 'val' are only allowed on top level or in objects

How declare compile time constant?



Solution 1:[1]

const vals cannot be in a class. For you, this means you need to declare it top-level, in an object, or in a companion object (which also is exactly what the error message says).

Since your value is private, a companion object is one of the two options you can use:

class TradersActivityTest {
    ...
    companion object {
        private const val ONE_TR = "no_wallets.json"
    }
}

Doing that makes it accessible to the class only.


The second option is top-level. However, note that this exposes it to the rest of the file, not just the one class:

private const val ONE_TR = "no_wallets.json"

...

class TradersActivityTest {
    ...
}

For the sake of completeness, the third option was using an object:

object Constants {
    const val ONE_TR = "no_wallets.json"
}

However, it needs to be public to be accessed. It can alternatively be internal, but it again depends on what you want to have access.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community