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.
CodePudding user response:
A simpler way to implement what you need is:
val colorMap = mapOf (
'A' to R.color.colorBgShade1,
'B' to R.color.colorBgShade2,
...
...
)
val char = 'G'
val bgColor = colorMap[char] ?: R.color.colorBgShade27
background.setTint(ContextCompat.getColor(context, bgColor)
CodePudding user response:
This is what you need.
val char = "G"
when {
char.equals("A", true) -> {
background.setTint(ContextCompat.getColor(context, R.color.colorBgShade1))
}
char.equals("B", true) -> {
background.setTint(ContextCompat.getColor(context, R.color.colorBgShade2))
}
char.equals("C", true) -> {
background.setTint(ContextCompat.getColor(context, R.color.colorBgShade3))
}
char.equals("D", true) -> {
background.setTint(ContextCompat.getColor(context, R.color.colorBgShade4))
}
char.equals("E", true) -> {
background.setTint(ContextCompat.getColor(context, R.color.colorBgShade5))
}
char.equals("F", true) -> {
background.setTint(ContextCompat.getColor(context, R.color.colorBgShade6))
}
char.equals("Z", true) -> {
background.setTint(ContextCompat.getColor(context, R.color.colorBgShade26))
}
else -> {
background.setTint(ContextCompat.getColor(context, R.color.colorBgShade27))
}
}
But the best way is that you should do it like this.
data class Alpha(val alpha:String , val color: Int)
fun generateData() {
val listAlpha = arrayListOf<Alpha>()
listAlpha.add(Alpha("A", R.color.colorBgShade1))
listAlpha.add(Alpha("B", R.color.colorBgShade2))
listAlpha.add(Alpha("C", R.color.colorBgShade3))
listAlpha.add(Alpha("D", R.color.colorBgShade4))
var char = "D"
val alphaFindResult = listAlpha.single { it.alpha.equals(char, true) }
background.setTint(ContextCompat.getColor(context, alphaFindResult.color))
}