2

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?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
testivanivan
  • 967
  • 13
  • 36
  • 10
    That by definition is not a constant because its value is determined at runtime. It is therefore against convention to give it a name in all-caps. – Tenfour04 Mar 20 '22 at 20:56
  • The warning you are getting is valid, as its not a constant. In normal class you have to create the companion object to provide the fields or methods without creating object of class. Otherwise you can also search for Object class in kotlin. – Anuj Sharma Mar 20 '22 at 22:03

3 Answers3

2

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.

Moshe Katz
  • 15,992
  • 7
  • 69
  • 116
1

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.

Navas pk
  • 331
  • 3
  • 17
0

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

Ehsan Ullah
  • 144
  • 3