Get the value of the first argument of the triple expression

I would like to use the value of the first argument in a ternary expression to do something like:

a() ? b(value of a()) : c

Is there any way to do this? a is a function that is expensive to run several times and returns a list. I need to do different calculations if the list is NULL. I want to express this in a three-dimensional expression.

I tried to do something like:

String a()
{
    "a"
}

def x
(x=a()) ? println(x) : println("not a")

But this is pretty ugly ...

+4
source share
4 answers

Perhaps you can wrap it with?

def result = a().with { x -> x ? "Got $x" : "Nope" }
+5
source

You can use groovy collect:

def result = a().collect { "Got $it" } ?: "Nope"

If you are worried about your () returning a list with zeros, you can use findAll.

def result = a().findAll { it }.collect { "Got $it" } ?: "Nope"
+2
source

, , , , memoization :

Closure<String> a = {
    'a'
}.memoize()

a() ? println(a()) : println("not a")
+1

:

Something tmp = a()
tmp ? b(tmp) : c
+1

All Articles