I was wondering if there is a simpler or shorter way to write repetitive conditions like x == 1 && y == 1 && z == 1?
Question posted in Android Studio
The official documentation can be found here.
The official documentation can be found here.
5
Answers
You could consider using predicates using
all
. For example:This will return
true
whenx==1
,y==1
, andz==1
.If the goal is to shorten what you want, there’s not much legroom as your boolean expression is already very concise. Some of the other answers have illustrated how to make what you want more readable, however.
When it is (exactly) repeated code, you should consider to extract the statement into a method and give a meaningfull name, which you know from the context where it is used. This makes the requirement (reading the code) easier to understand, at the point where it is used. And it makes it also easier to spot the it is always the same condition.
I cannot think of a shorter statement for the condition, but a method extraction will improve your code readability, which should be your overall goal.
If it makes sense you could hold those variables in a class
And compare your instance with
XYZ(1, 1, 1)
;Or if it’s just those three variables, you could write
You can make a convenience function for this kind of repeated code (or if you just need it to be more readable, or safer to edit):
But no, there isn’t any other shorthand built into the language as far as I’m aware – conditions like
x == 1
chained with boolean operators are about as simple as it can get! If you want to check multiple things without repeating yourself,any
andall
make that easy, while being flexible for all kinds of situations, and allowing the user to put together the functionality they need with those more general functions.If you specifically want a version of
all
that does a simple comparison to a single value, and doesn’t require creating an iterable likelistOf
, you have to write your own with those tools (which is basically what I’ve done). It’s up to you if you think it’s worth it!