Issue
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
- Scope function
run {}
is called on an objectstudent
equals
is replaced by==
to compare boolean as well asnull
values- 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
Answered By - kirill leonov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.