Search code examples
kotlinarraylistdata-class

How do I get the value from an ArrayList by using an "external" variable for comparing in Kotlin?


I am trying to get one value from an Array with a data class in an elegant way depending on a Boolean type value. Here is an example:

...
private val isDone = true/false
...
private fun color(key: String): Int {
    val colors = arrayListOf(
        Color(TEXT, R.color.text_light, R.color.text_night),
        Color(BACK, R.color.background_light, R.color.background_night),
        ...
    )

    //Wanna achieve something like this
    val color = colors.find { it.key == key }.if { isDone } // if Done is true, the colorA should be retured, if not then the colorB.

    return color 
}

This is the date class I use:

data class Color(val key: String, @ColorRes val colorA: Int, @ColorRes val colorB: Int)

Is there a simple way by using some extensions of ArrayList to achieve that? I do not want to use .forEach loop or similar.


Solution

  • That "some extensions of ArrayList" is find, which you are already using.

    After we find it, we can use let to bind the found color to a name, and then use an if expression to check isDone.

    val color = colors.find { it.key == key }?.let { found -> 
        if (isDone) { found.colorA } else { found.colorB }
    }
    

    Note that color is of type Int?. It is nullable because it will be null when key is not found. You should think about what to do when this happens.

    Also note that isDone is a val, which is likely to be unintentional (?)