Groovy 上的三元快捷方式

Ternary shortcut on Groovy

我知道三元运算符本身已经是一个快捷方式,但我仍然想知道groovy中是否有这个快捷方式:

String typeFilter = (params?.type) ? params.type : ""

我在这里要做的是:

"If the HashMap params has a type key, assign the value of that key to typeFilter, otherwise, assign typeFilter with an empty string"

我在想是否可以避免输入两次 params?.type,或者这是我给定场景的最短代码?感谢您的反馈。

您实际上刚刚描述了 elvis 运算符:

String typeFilter = params.type ?: ""

更多相关信息:http://docs.groovy-lang.org/latest/html/documentation/#_elvis_operator

只要确保您了解 Groovy 真相 (http://mrhaki.blogspot.com/2009/08/groovy-goodness-tell-groovy-truth.html) 特别是当涉及到 0nullempty 的价值时。考虑一下:

params.age = 0
...
// elsewhere in the code
params.age = params.age ?: 6 // if no age provided default to 6

这会将 params.age 设置为 6,尽管 if 已经用 0!

初始化

虽然@defectus 提供的答案大体上是正确的,但也存在一些特殊情况。考虑以下示例:

def s = ''
def r = s.empty ?: 'notempty'
assert r == true

在上面的示例中,返回 true 而不是空字符串。虽然对于某些人来说这可能是显而易见的,但当我前段时间面对它时,这是一个真正的问题 ;)

您是否考虑过具有空值的键 type 的极端情况?如果发生这种情况,Elvis 操作员将 return RHS。这在您要实现的目标的上下文中可能无关紧要,但它不符合您的要求(从字面上看):

"If the HashMap params has a type key, assign the value of that key to typeFilter, otherwise, assign typeFilter with an empty string"

例子。 (我使用 'none' 而不是空字符串来使输出更清晰。)

println( [:].type ?: 'none' )
=> none

println( [type: 42].type ?: 'none' )
=> 42

// But do you want null or 'none' in this case?
println( [type: null].type ?: 'none' )
=> none