I would like to get to use the value of the first argument in a ternary expression to do something like:
a() ? b(value of a()) : c
Is there a way to do this? a is a function that is costly to run multiple times and that return a list. I need to make different computations if the list is null. I want to express it in a ternary expression.
I tried to do something like:
String a()
{
"a"
}
def x
(x=a()) ? println(x) : println("not a")
But it's quite ugly...
You could maybe wrap it in a with?
def result = a().with { x -> x ? "Got $x" : "Nope" }
You can use a groovy collect:
def result = a().collect { "Got $it" } ?: "Nope"
If you are worried about your a() returning a list containing nulls you can use findAll.
def result = a().findAll { it }.collect { "Got $it" } ?: "Nope"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With