kotlinconstantscompanion-objectprimary-constructorval

Kotlin. How to declare constant?


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?


Solution

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