Home > other >  Android/Kotlin: Chaining method calls with condition
Android/Kotlin: Chaining method calls with condition

Time:10-27

I have an amount of - lets say 4 - methods. And I only want to execute the next one if the previous has an expected result (e.g. Boolean). Something like this:

if (isUserLoggedIn()) {
   if (userHasDoneTour()) {
     if(otherConditionalMethod()) {
        finalMethod()
     }
   }
}

Is there a better way to chain these conditional method calls?

CodePudding user response:

if you don't do anything else in the outer if blocks it's better to combine them to a single if statement like

if (isUserLoggedIn() && userHasDoneTour() && otherConditionalMethod()) {
    finalMethod()
}

CodePudding user response:

For long condition chains and better readability you can use kotlin operators.

val isEveryConditionTrue = isUserLoggedIn()
    .and(userHasDoneTour())
    .and(otherConditionalMethod())

if (isEveryConditionTrue) {
    finalMethod()
}

Here is few operators for boolean:

1) true && false -> true.and(false) // false
2) true || false -> true.or(false) // true
3) !true -> true.not() // false
  • Related