0

I have a field and I need to compare if the given field is equal to one of my constants. I have three constants in total:

 companion object {
        private const val NEGATIVE_POSITION = -1
        private const val ZERO_POSITION = 0
        private const val POSITIVE_POSITION = 1
    }

For comparison, I decided to use range:

if(position in NEGATIVE_POSITION..POSITIVE_POSITION) 

But in this case, my code becomes less obvious, because it is not clear what the values that are in the range mean (because ZERO_POSITION not used).

Of course, I could use this method, but this method seems very cumbersome to me:

if(position == NEGATIVE_POSITION  || position == ZERO_POSITION || position == POSITIVE_POSITION)

Tell me please, is there a more elegant way to perform such a comparison, while not losing the meaning of each constant?

Please, help me.

testivanivan
  • 967
  • 13
  • 36

2 Answers2

3

You can keep a list of all the constants and do your in check with the List instead of a Range.

companion object {
    private const val NEGATIVE_POSITION = -1
    private const val ZERO_POSITION = 0
    private const val POSITIVE_POSITION = 1

    private val ALL_POSITIONS = listOf(NEGATIVE_POSITION, ZERO_POSITION, POSITIVE_POSITION)
}

// ...

if(position in ALL_POSITIONS) //...
Tenfour04
  • 83,111
  • 11
  • 94
  • 154
  • 1
    Yeah it's not really a range, it's just a set of three distinct values (I'd use a `Set`!) that just happens to look like a range. If you're asking "does this value fall between this start value and this end value" then you need a range, if you're asking "is this value a member of this set of items" then you want some kind of collection – cactustictacs Jun 07 '22 at 18:28
2

you should move your constants for a enum class like this:

enum class Constants(val value: Int) {
    NEGATIVE_POSITION(-1),
    ZERO_POSITION(0),
    POSITIVE_POSITION(1);

    fun findPosition(position: Int): Constants? {
        return values().find {
            it.value == position
        }
    }

    fun isPositionExist(position: Int): Boolean {
        return values().any {
            it.value == position
        }
    }
}

if you add a new constant in future there's nothing to change

Mohmmaed-Amleh
  • 383
  • 2
  • 11
  • 1
    Shouldn't the latter function use `any` instead of `all`? (Also, I'd suggest `Position` for the class name, and maybe `forValue()` and `hasValue()` for the functions.) – gidds Jun 07 '22 at 18:37