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?
In Kotlin, val is also used for declaring a variable. Both "val" and "const val" are used for declaring read-only properties of a class. The variables declared as const are initialized at the runtime. val deals with the immutable property of a class, that is, only read-only variables can be declared using val.
Kotlin const variable can be declared at the top of the programming language and it can be used throughout the file scope. private const val My_TOP_LEVEL_CONST_VAL = "Type 1--> Example of Top Level Constant Value" fun main() { println(My_TOP_LEVEL_CONST_VAL); }
Answer: Companion object is not a Singleton object or Pattern in Kotlin – It's primarily used to define class level variables and methods called static variables. This is common across all instances of the class.
const val
s 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).
Given it's private, a companion object
one of the two options you can apply:
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 { ... }
And just for the completeness of this answer, as I mentioned, the third option was an object:
object Constants { const val ONE_TR = "no_wallets.json" }
But it needs to be public to be accessed. Or alternatively internal, but it again depends on your target scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With