Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 626
Alex Avatar asked Apr 27 '19 12:04

Alex


People also ask

What is difference between Val and const Val in Kotlin?

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.

What is private const Val in Kotlin?

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); }

What is a kotlin companion object?

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.


1 Answers

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).

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.

like image 103
Zoe stands with Ukraine Avatar answered Sep 20 '22 08:09

Zoe stands with Ukraine