Functional Groovy switch statement
In the previous post I showed how to replace chained if-else statements in Groovy with one concise switch. It was done for the special case of if-stement where every branch was evaluated using the same condition function. Today I want to make a generalization of that technique by allowing to use different conditionals.
Suppose your code looks like this:
As long as every condition operates on the same parameter, you can replace the entire chain with a switch. In this scenario param
becomes a switch parameter and conditions become case
parameters of Closure type. The only thing we need to do is to override Closure.isCase()
method as I described in the previous post. The safest way to do it is to create a category class:
Now we can replace if-statement with the following switch:
We can actually go further and extract in-line closures:
After which the code becomes even more readable: