As mentioned in our previous post where we discussed the flow of a gradle custom task, we will now talk about how we can define a custom method inside the Gradle script so that we can arrange our coding for a better understanding.

In one approach of writing methods are given below:

ext.myCustomMethod = {  parameter_1, parameter_2 ->



The above declaration of method will be globally available along the project. You can invoke this subroutine anywhere from the project. To invoke the method:

project.myCustomMethod (parameter_1, parameter_2)

or simply 


In the above, use of ext will restrict the scope to where it is defined. Suppose if it is under a task, the scope of that method will lie only inside the task. If it is defined inside a project, it will be available throughout the project.

task myTask {
    ext.myCustomMethod= { parameter_1, parameter_2->
        // Method body

    doLast {
        myCustomMethod(param_1, param_2) // call to 'myCustomMethod'

The advantage of using the above approach is supposed you have different tasks, you are allowed to use the same method names without any conflict. Some more points about methods in Gradle:

1.  As Gradle is purely based on groovy, you can write methods without specifying any return type. Ye,s it will work. In the above example, the method can return anything without specifying a return type. (optionally you can specify ‘def” as a groovy standard). For instance, it returns a list object you can collect the method return as follows:

List<String> list = myCustomMethod(param_1,param_2);

2. I have noticed one more characteristic of Gradle methods. You must define the method before calling it. If you are succeeded in calling the method before implementing it, please let me know in comments as it shows an error for me.

Also Read:  How to setup a Gradle continuous build for your java project

Click If you want to explore more about using methods in gradle.

Share this article:

Leave a Reply

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