android gradle plugin - Why can't groovy deal with curly braces?

In an Android Studio (and presumably ANY) gradle file, the following code works:

task build {
}

And one minor change causes a complete meltdown:

task build
{
}

This has come up in other threads before, but in the context of fixing the build files. My question is why can't gradle/groovy be made to deal with either bracing style? Many other languages cope just fine with it, so what's the big deal here?

2 Answers

  1. David- Reply

    2019-11-16

    It's actually all right there in the error message:

    build file '.../build.gradle': 80: Ambiguous expression could be a parameterless 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 explicit semicolon ';' @ line 80, column 1.
    

    Because of a Groovy syntax sugar to make methods with a lambda as the last parameter look line language constructs, the following code blocks:

    task build {}
    task build2(type: Copy) {}
    

    are equal to their more regular form:

    task build({})
    task build(type: Copy, {})
    

    Now, you do not really want those curly braces there to delimit a regular code block, but a Groovy lambda, which should be passed as a parameter to the build method.

    Yet from the looks of it, Groovy can't really decide if it really is a lambda being passed as a parameter to the method in the previous line or an unrelated code block when you put a newline in between. And there you go, an ambiguousness as described in the error message, right there.

    Following the advice in the error message, you can also use the following syntax instead of the one where you are escaping the new-line character:

    task build
    { -> 
    }
    

    Finally, the task keyword used to invoke the dynamic method (named build in your example) is not Groovy specific, but a Gradle DSL feature.

  2. Denny- Reply

    2019-11-16

    In case anyone reading this is wondering, the work-around is simple enough.

    task build \
    {
    }
    

    I was just wondering as to the "why"...

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>