[英]Inline Conditional Map Literal in Groovy
在 Groovy 中使用 Maps/JsonBuilder 處理一些翻譯/映射功能。
有可能(無需在 map 文字創建之外創建額外代碼).. 有條件地包含/排除某些鍵/值對嗎? 以下是一些事情..
def someConditional = true
def mapResult =
[
"id":123,
"somethingElse":[],
if(someConditional){ return ["onlyIfConditionalTrue":true]}
]
預期結果:如果 someConditional if false,mapResult 中將只存在 2 個鍵/值對。
如果 someConditional 如果為真,則所有 3 個鍵/值對都將存在。
請注意,如果我創建方法/並將其拆分,我確信它可以完成。為了保持簡潔,我希望將內容保留在 map 創建中。
你可以幫助自己與with
:
[a:1, b:2].with{
if (false) {
c = 1
}
it
}
有一個小幫手:
Map newMap(m=[:], Closure c) {
m.with c
m
}
例如:
def m = newMap {
a = 1
b = 1
if (true) {
c = 1
}
if (false) {
d = 1
}
}
assert m.a == 1
assert m.b == 1
assert m.c == 1
assert !m.containsKey('d')
或傳遞初始地圖:
newMap(a:1, b:2) {
if (true) {
c = 1
}
if (false) {
d = 1
}
}
由於Groovy的2.5,存在一種替代with
稱為tap
。 它的工作原理with
類似with
但不返回閉包的返回值,而是委托。 所以可以這樣寫:
[a:1, b:2].tap{
if (false) {
c = 1
}
}
沒有這樣的語法,您能做的就是
def someConditional = true
def mapResult = [
"id":123,
"somethingElse":[]
]
if (someConditional) {
mapResult.onlyIfConditionalTrue = true
}
我同意Donal的觀點,沒有地圖創建之外的代碼很難。
至少您必須實現自己的ConditionalMap,這雖然有點工作,但是完全可行。
每個元素可以有自己的條件,例如
map["a"] = "A"
map["b"] = "B"
map.put("c","C", true)
map.put("d","D", { myCondition })
etc...
在這里有一個不完整的示例(我只是放置了 , get , keySet , 值和大小來說明,而沒有輸入-但您這里可能不需要類型?),您可能將不得不實現其他幾個(isEmpty,containsKey等)。 ..)。
class ConditionalMap extends HashMap {
/** Default condition can be a closure */
def defaultCondition = true
/** Put an elemtn with default condition */
def put(key, value) {
super.put(key, new Tuple(defaultCondition, value))
}
/** Put an elemetn with specific condition */
def put(key, value, condition) {
super.put(key, new Tuple(condition, value))
}
/** Get visible element only */
def get(key) {
def tuple = super.get(key)
tuple[0] == true ? tuple[1] : null
}
/** Not part of Map , just to know the real size*/
def int realSize() {
super.keySet().size()
}
/** Includes only the "visible" elements keys */
def Set keySet() {
super.keySet().inject(new HashSet(),
{ result, key
->
def tuple = super.get(key)
if (tuple[0])
result.add(key)
result
})
}
/** Includes only the "visible" elements keys */
def Collection values() {
this.keySet().asCollection().collect({ k -> this[k] })
}
/** Includes only the "visible" elements keys */
def int size() {
this.keySet().size()
}
}
/** default condition that do not accept elements */
def map = new ConditionalMap(defaultCondition: false)
/** condition can be a closure too */
// def map = new ConditionalMap(defaultCondition : {-> true == false })
map["a"] = "A"
map["b"] = "B"
map.put("c","C", true)
map.put("d","D", false)
assert map.size() == 1
assert map.realSize() == 4
println map["a"]
println map["b"]
println map["c"]
println map["d"]
println "size: ${map.size()}"
println "realSize: ${map.realSize()}"
println "keySet: ${map.keySet()}"
println "values: ${map.values()}"
/** end of script */
您可能會將所有錯誤條件映射到一個公用密鑰(例如"/dev/null"
, ""
等),然后在以后將其作為合同的一部分刪除。 考慮以下:
def condA = true
def condB = false
def condC = false
def mapResult =
[
"id":123,
"somethingElse":[],
(condA ? "condA" : "") : "hello",
(condB ? "condB" : "") : "abc",
(condB ? "condC" : "") : "ijk",
]
// mandatory, arguably reasonable
mapResult.remove("")
assert 3 == mapResult.keySet().size()
assert 123 == mapResult["id"]
assert [] == mapResult["somethingElse"]
assert "hello" == mapResult["condA"]
您可以使用傳播運算符為地圖和列表執行此操作:
def t = true
def map = [
a:5,
*:(t ? [b:6] : [:])
]
println(map)
[a:5, b:6]
這在 v3 中有效,在以前的版本中沒有嘗試過。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.