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?
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:
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:
The second form also means that if your
counter
would be a mutablevar
(instead of an immutableval
), then themaxValue
would also change when thecounter
changes.