Groovy函数没有括号和参数以大写字母开头导致错误

时间:2015-08-28 06:59:23

标签: groovy

我有一个包含成分列表的类,并提供了一个功能SERVE,可以打印这些成分。

class CookDSL {
  List<String> ingredientsToCook

  CookDSL(List<String> ingredients){
     ingredientsToCook=ingredients
  }

  void SERVE(Closure closure){closure(ingredientsToCook)}
}

这是返回上述类的实例的DSL函数:

CookDSL COOK(List<String> ingredients){
  new CookDSL(ingredients)
}

现在我可以使用如下所示的DSL,并通过打印所有成分正常工作:

def ingredients = ["X", "Y", "Z"]
COOK ingredients SERVE {it-> println(it)}

输出:

[X, Y, Z]

为了保持上述DSL的一致性,我尝试将成分命名为Ingredients,而Groovy并不喜欢它。

def Ingredients = ["X", "Y", "Z"]
COOK Ingredients SERVE {it-> println(it)}

输出:

startup failed:
Script1.groovy: 16: unexpected token: Ingredients @ line 18, column 10.
   COOK Ingredients SERVE {it-> println(it)}
        ^

1 error

如果Ingredients变量用括号括起来,它可以正常工作:

def Ingredients = ["X", "Y", "Z"]
COOK(Ingredients) SERVE {it-> println(it)}

输出:

[X, Y, Z]

在某些情况下,不确定我是否做错了什么或Groovy在使用以大写字母开头的变量时有限制?

Groovy版本:2.3.8

1 个答案:

答案 0 :(得分:0)

正如@tim_yates所说,大写字母可能会使解析器混乱,也许它将它们理解为类标识符。我通常看起来DSLs uncapitalized

class CookDSL {
  List<String> ingredientsToCook

  void serve(Closure closure){closure(ingredientsToCook)}
}

CookDSL cook(List<String> ingredients){
  new CookDSL(ingredientsToCook: ingredients)
}

def ingredients = ["X", "Y", "Z"]
cook ingredients serve {it-> println(it)}

如果您将结果设置为var,则不会抱怨。可能它不再含糊不清了:

def COOK = { ingredients -> new CookDSL(ingredientsToCook: ingredients) }

def Ingredients = ["ribs", "bacon", "pineapple"]
def cooked = COOK Ingredients SERVE { "cooked $it" }
assert cooked == ["cooked ribs", "cooked bacon", "cooked pineapple"]