Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 645
kirill leonov Avatar asked Oct 22 '25 16:10

kirill leonov


1 Answers

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
like image 141
kirill leonov Avatar answered Oct 25 '25 09:10

kirill leonov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!