获取三元表达式第一个参数的值

Get the value of the first argument of the ternary expression

我想使用三元表达式中第一个参数的值来执行如下操作:

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

有办法吗? a 是一个函数,它对 运行 多次是昂贵的,并且 return 是一个列表。如果列表为空,我需要进行不同的计算。 我想用三元表达式来表达。

我尝试做类似的事情:

String a()
{
    "a"
}

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

但是真的很难看...

不知道三元运算符是否可行,但也许记忆是解决方案:

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

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

怎么样:

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

你可以用 with 把它包起来吗?

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

您可以使用 groovy 收集:

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

如果您担心 a() 返回包含空值的列表,您可以使用 findAll。

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