Search code examples
javaandroidkotlinequals

In Kotlin, how to refactor "if else" and use "when" instead of it with equals ignore case comparison?


I want to refactor this code for using "when" instead of "if else". How can I use Kotlin's when(char) with ignore case for my situation?

    if(char.equals("A", true))
        background.setTint(ContextCompat.getColor(context, R.color.colorBgShade1))
    else if(char.equals("B", true))
        background.setTint(ContextCompat.getColor(context, R.color.colorBgShade2))
    else if(char.equals("C", true))
        background.setTint(ContextCompat.getColor(context, R.color.colorBgShade3))
    else if(char.equals("D", true))
        background.setTint(ContextCompat.getColor(context, R.color.colorBgShade4))
    else if(char.equals("E", true))
        background.setTint(ContextCompat.getColor(context, R.color.colorBgShade5))
    else if(char.equals("F", true))
        background.setTint(ContextCompat.getColor(context, R.color.colorBgShade6))
    ...
    else if(char.equals("Z", true))
        background.setTint(ContextCompat.getColor(context, R.color.colorBgShade26))
    else
        background.setTint(ContextCompat.getColor(context, R.color.colorBgShade27))

Please let me know if there is a way to do this in a good way.


Solution

  • Maybe this is what you want:

    val ch = 'A'
    val src = when (ch.toUpperCase()) {
        'A' -> R.color.colorBgShade1
        'B' -> R.color.colorBgShade2
        // ...
        'Z' -> R.color.colorBgShade26
        else -> R.color.colorBgShade27
    }
    background.setTint(ContextCompat.getColor(context, src))
    

    But using Map is always a better way for such problem.