I have a function like this and it returns the ENUM data.
if (shouldShowCTA) {
if (progress) {
when (type) {
TYPE1 -> TYPE1_PROGRESS
TYPE2 -> TYPE2_PROGRESS
else -> null
}
} else if (completed) {
when (type) {
TYPE1 -> TYPE1_COMPLETED
TYPE2 -> TYPE2_COMPLETED
else -> null
}
} else {
null
}
} else {
null
}
Here I have a repeated code of When condition. How can I combine all the if and else if at one condition?
CodePudding user response:
You could simplify it like this:
if (shouldShowCTA) {
when {
type == TYPE1 && progress -> TYPE1_PROGRESS
type == TYPE2 && progress -> TYPE2_PROGRESS
type == TYPE1 && completed -> TYPE1_COMPLETED
type == TYPE2 && completed -> TYPE2_COMPLETED
else -> null
}
} else {
null
}
Just a note that this way you lose when
's exhaustiveness, since it's not when(value) {
syntax but when {
CodePudding user response:
if(!shouldShowCTA)
return null
if(progress)
return when (type) {
Type1 -> {}
Type2 -> {}
else -> null
}
if(completed)
return when (type) {
Type1 -> {}
Type2 -> {}
else -> null
}
return null