Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the value of the first argument of the ternary expression

Tags:

groovy

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...

like image 327
Heschoon Avatar asked Jan 09 '23 14:01

Heschoon


2 Answers

You could maybe wrap it in a with?

def result = a().with { x -> x ? "Got $x" : "Nope" }
like image 54
tim_yates Avatar answered Jan 11 '23 05:01

tim_yates


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"
like image 30
dspano Avatar answered Jan 11 '23 05:01

dspano