33

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?

Alex
  • 1,857
  • 4
  • 17
  • 34

1 Answers1

43

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.

Community
  • 1
  • 1
Zoe
  • 27,060
  • 21
  • 118
  • 148
  • "companion object" - is a analog of static in Java ? – Alex Apr 27 '19 at 13:27
  • @Alex yes and no. A companion object is technically a singleton in terms of Java interop (if you've called a companion object from Kotlin, you might've noticed the syntax is `SomeClassName.COMPANION.someField`. They act static, but not in the "traditional" way as with Java. See [the docs](https://kotlinlang.org/docs/reference/object-declarations.html#companion-objects), or even better, [this answer](https://stackoverflow.com/a/38382433/6296561). – Zoe Apr 27 '19 at 13:31
  • 17
    Why const is not allowed in a class ?? Why is it allowed only inside object or companion object or top level ?? Is there any reason for that ?? – K Pradeep Kumar Reddy May 08 '20 at 14:42