Vincent Hsiung Vincent Hsiung - 4 months ago 22
Groovy Question

gradle task method syntax in build.gradle

I am new to gradle and groovy,I am reading the usr guide of Gradle, and have some syntax questions on task method:

task intro(dependsOn: hello) {
doLast { println "I'm Gradle" }
}


Question 1:in above code, which method is called in
Project
API ? I know there are four overload in API:

Task task(String name, Closure configureClosure);
Task task(Map<String, ?> args, String name, Closure configureClosure);
Task task(Map<String, ?> args, String name) throws InvalidUserDataException;
Task task(String name) throws InvalidUserDataException;


but the parameter such as
intro(dependsOn: hello)
or
copy(type: Copy)
make me confused, what it should be if add parentheses?

Question 2: why << is shorthand for
doLast
method? I mean there is a
leftshift
method in
Task
API ? what is diff between them?

Question 3: why can use
tasks.create()
method in build.gradle 17.1. Defining tasks,I did not see
tasks
property in
Project
API or in
AbstractProject
source code.

Answer

In this particular case:

task intro(dependsOn: hello) {
   doLast { println "I'm Gradle" }  
}

the following method will be invoked:

Task task(Map<String, ?> args, String name, Closure configureClosure);

Since gradle uses a specific DSL it may be hard to tell but:

  1. Q1

    • intro is a String name argument
    • dependsOn: hello which is equivalent to [dependsOn: hello] (a Map) is Map<String, ?> args
    • { doLast { println "I'm Gradle" } } is Closure configureClosure
  2. Q2

<< is a shorthand for doLast just to make it more concise. You can use doLast, <<, leftShift - it's all the same. leftShift is overridden - see here

  1. Q3

There's no such method tasks but getTasks, see here. This is how groovy works - if method is a getter () and get can be omitted, so project.getTasks() is equivalent to project.tasks.