Home > Enterprise >  Kotlin. How to check if value is in range?
Kotlin. How to check if value is in range?

Time:06-08

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.

CodePudding user response:

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) //...

CodePudding user response:

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

  • Related