How to write and call methods in gradle script

As mentioned in our previous post where we discussed about 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 is given below:

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:

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.

The advantage of using the above approach is suppose you have different tasks, you are allowed to use 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. Yes 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 characteristics of gradle methods. You must define the method before calling it. If you are succeeded calling the method before implementing it, please let me know in comments as it shows an error for me.

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 *