当跨越多行时,是否在Groovy中省略括号?

当跨越多行时,是否在Groovy中省略括号?,groovy,dsl,builder,Groovy,Dsl,Builder,在groovy中处理类似dsl的简单SQL,我有一些构建器类来创建select语句 e、 g 及 等等 在我的脚本中,我现在可以这样说: select all from foo where {tuple, args -> tuple.get(id) == args[0]}; 然而,如果我在其中添加新行,那就是一个错误 select all from foo where {tuple, args -> tuple.get(id) == args[0]}; groovy.lang

在groovy中处理类似dsl的简单SQL,我有一些构建器类来创建select语句

e、 g

等等

在我的脚本中,我现在可以这样说:

select all from foo where {tuple, args -> tuple.get(id) == args[0]};
然而,如果我在其中添加新行,那就是一个错误

select all 
from foo 
where {tuple, args -> tuple.get(id) == args[0]};

groovy.lang.MissingMethodException: 
No signature of method: foo.Foo.from() is applicable for argument types:
 (clojure.lang.Keyword) values: [:foo]|Possible solutions: grep(), find(), 
          find(groovy.lang.Closure), grep(java.lang.Object), wait(), any()
这只是解析Groovy时可选括号的副作用吗

凭直觉,我在每一行的末尾加上反斜杠,这似乎很有效。e、 g

select all \
from foo \
where {tuple, args -> tuple.get(id) == args[0]};

有更好的方法吗?

没有。Groovy解析器将假定语句在第一行之后完成,插入一个
在末尾,除非它知道行继续(例如,当有一个开括号或当您转义EOL时)


这就是不需要分号的语言的缺点。

我想@Aaron是对的。或者,您可以允许在闭包内调用方法,并将方法调用委托给查询生成器:

class QueryBuilder {

  def projection
  def origin
  def condition

  def call(closure) {
    def hydrated = closure.rehydrate this, this, this
    hydrated()
    "select $projection from $origin"
  }

  def select(projection) {
    this.projection = projection
  }

  def from(origin) {
    this.origin = origin
  }

  def where(closure) {
    condition = closure
  }

  def propertyMissing(String property) { property }
}

def sql = new QueryBuilder().call {
  select all 
  from foo 
  where {tuple, args -> tuple.get(id) == args[0]};
}

assert sql == "select all from foo"
我没有完成
where
部分,但我想你已经明白了

select all \
from foo \
where {tuple, args -> tuple.get(id) == args[0]};
class QueryBuilder {

  def projection
  def origin
  def condition

  def call(closure) {
    def hydrated = closure.rehydrate this, this, this
    hydrated()
    "select $projection from $origin"
  }

  def select(projection) {
    this.projection = projection
  }

  def from(origin) {
    this.origin = origin
  }

  def where(closure) {
    condition = closure
  }

  def propertyMissing(String property) { property }
}

def sql = new QueryBuilder().call {
  select all 
  from foo 
  where {tuple, args -> tuple.get(id) == args[0]};
}

assert sql == "select all from foo"