Home > database >  Kotlin. How to declare constant?
Kotlin. How to declare constant?

Time:03-22

I have class, which in primary constructor has some fields:

class SomeData(val counter: Int...) { // some logic}

I need to create a constant. I usually do it like this:

 companion object {
     private const val MAX_VALUE = 1000
 }

But in my case, to declare a constant, I need to use a field from the class SomeData. But to access the field counter from SomeData class I need to create an instance of this class and then access the field.

Is it normal practice to do something like this?

Or is it better to declare this constant inside the class:

private val MAX_VALUE = counter/ 2

But in that case, Android Studio warns me:

Private property name 'MAX_VALUE ' should not contain underscores in the middle or the end

How should I declare a constant?

CodePudding user response:

Constant is something default value which never changed through out the execution and it never depend on any other value dynamically. You can create as below

companion object { private const val CONSTAN_NAME = "value" }

This is immutable in nature & by declaring this way you are telling to compiler that this is a inline constant & which will directly replace with value during run time. So optimized way creating constant.

CodePudding user response:

If your MAX_VALUE is based on other data in the object, then it is by definition not a constant.

What you need instead is a read-only property. There are two easy ways to create this:

First, what you already did:

class SomeData(val counter: Int...) {

    private val maxValue = counter / 2

    // some logic
}

Note that the name maxValue is using camel-case, not upper-snake-case.

Second, if you want to be a little more verbose, you can use an explicit getter:

class SomeData(val counter: Int...) {

    private val maxValue: String
        get() = counter / 2

    // some logic
}

The second form also means that if your counter would be a mutable var (instead of an immutable val), then the maxValue would also change when the counter changes.

CodePudding user response:

create a file Constants and inside that file just create constants like

const val DATABASE_NAME = "database-xyz"

and if you create a companion object then it's not a good practice as it will create instance of that class too and it will get resources until you don't destroy it after usage

  • Related