4

我正在尝试几个 gradle 基础知识。这是我的 gradle 文件“build.gradle”的样子:

task hello
{
    doLast
    {
        println 'Hello World!'
    }
}

这会导致以下错误:

D:\DevAreas\learn-gradle>gradle -q hello

FAILURE: Build failed with an exception.

* Where:
Build file 'D:\DevAreas\learn-gradle\build.gradle' line: 2

* What went wrong:
Could not compile build file 'D:\DevAreas\learn-gradle\build.gradle'.
> startup failed:
  build file 'D:\DevAreas\learn-gradle\build.gradle': 2: Ambiguous expression could be a parameterle
ss closure expression, an isolated open code block, or it may continue a previous statement;
   solution: Add an explicit parameter list, e.g. {it -> ...}, or force it to be treated as an open
block by giving it a label, e.g. L:{...}, and also either remove the previous newline, or add an exp
licit semicolon ';' @ line 2, column 1.
     {
     ^

  1 error


* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more l
og output.

如果我像这样对构建文件进行小的修改

[请注意,我已将括号从第二行移至第一行]

task hello{
    doLast
    {
        println 'Hello World!'
    }
}

我看到了输出

Hello World!

没有问题。

括号在gradle中是个大问题吗?通过将括号放在第二行中,我做错了什么?

4

1 回答 1

6

与使用分号推断的其他语言一样,换行符在 Groovy 中有所不同。第一个片段被解析为task hello; { ... },这是不明确的(无法确定第二个语句是块还是闭包),因此 Groovy 语法无效。无论如何,这不是您想要的。您希望闭包与hello任务相关联。为避免此类意外,我建议遵循 Java 大括号样式。

于 2012-07-08T18:11:50.480 回答