Search code examples
kotlinbooleanpredicatechain

How to simplify chain of predicates in Kotlin


I have a chain of predicate clauses, something like this

student?.firstName?.equals("John") ?: false &&
student?.lastName?.equals("Smith") ?: false &&
student?.age?.equals(20) ?: false &&
student?.homeAddress?.equals("45 Boot Terrace") ?: false &&
student?.cellPhone?.startsWith("123456") ?: false

I have found that instead of && it's possible to switch to Boolean predicate and(), but overall it doesn't make code more concise.

Is there is a way in Kotlin to simplify such expression?


Solution

  • Thanks everyone who participated! Here is a final version of the code with notes:

    student?.run {
      firstName == "John" &&
      lastName == "Smith" &&
      age == 20 &&
      homeAddress == "45 Boot Terrace" &&
      cellPhone.orEmpty().startsWith("123456")
    } ?: false
    
    1. Scope function run {} is called on an object student
    2. equals is replaced by == to compare boolean as well as null values
    3. return type of scope function is nullable, so elvis operator is used ?: false. Another option is to use == true, but it's your personal preference