Details
-
Improvement
-
Status: Open
-
Minor
-
Resolution: Unresolved
-
4.0.0-alpha-2
-
None
Description
In some other languages (Scala, Python, Haskell, Java 14 switches) every statement like if..else, for, switch... is indeed an expression that returns a value (usually the last one computed is implicitly returned as in Groovy).
Would it be possible to include something like conditional expression, for comprehensions and switch expressions as a native groovy feature? I think it would simplify writing DSLs and maybe in some cases making groovy code neater and readable
Using closures it is possible to write "conditional expressions" without using the conditional operator, something like:
def pillToTake = { if(candidate.name == "Neo") "red" else "blue" }.call()
but maybe if groovy supports expression this could be written as
def pillToTake = if candidate.name == "Neo" then "red" else "blue"
or maybe using switch expression to include more complex cases
def trainingSchedule = switch(date) {
case { isHoliday(it) }: return ['Rest']
case { date.dayOfWeek in [MONDAY, FRIDAY] }: return ['Run 15m', '40 Push-Ups', '20 Crunches']
case {date.dayOfWeek.is(WEDNESDAY) }: return ['Run 10m', '50 Tractions', '30 Squats']
default: return ['Run 30m']
}
I've not really dug deep in how the groovy compiler works but maybe recognizing these expression, "wrapping" them in a closure and calling that closure could be done automatically?
For comprehensions maybe are a little bit more tricky to implement as a native groovy feature and using .collect(..) the code is equally readable, but maybe in some cases one could prefer to use a different construct
Actual groovy code:
def prices = stocks.filter { it.market == "NASDAQ"}.collect{ getPriceFor(it) }
Using for comprehension:
def prices = [getPriceFor(stock) for stock in stocks if stock.market == "NASDAQ"]
It is just a matter of preference which one is more readable but this could simplify the "flow" of the code in some cases.