Simple gradle build file build error

2019-05-07 08:32发布

问题:

I am trying out several gradle basics. Here is how my gradle file "build.gradle" looked:

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

This causes the following error:

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.

If I make a minor modification to the build file like so

[Please NOTE that I have moved the parenthesis from second line to first line]

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

I see the output

Hello World!

with out issues.

Is parenthesis such a big problem in gradle? What was I doing so wrong by placing the parenthesis in the second line?

回答1:

As with other languages that use semicolon inference, the newline makes a difference in Groovy. The first snippet gets parsed as task hello; { ... }, which is ambiguous (can't decide if the second statement is a block or a closure) and hence invalid Groovy syntax. It's not what you want anyway; you want the closure to be associated with the hello task. To avoid such surprises, I recommend to follow the Java braces style.



标签: build gradle