St.Antario
St.Antario

Reputation: 27425

The 4.times closure understanding

The gradle build script defined as follows:

4.times { counter ->
    task "task$counter" << {
        println "I'm task number $counter"
    }
}

define 4 different tasks with the names task1, task2, task3, task4. So what 4.times actually is? Is it just a closure which in that case applies 1 argument and called 4 times?

So is it just a syntax sugar?

Upvotes: 0

Views: 45

Answers (1)

Opal
Opal

Reputation: 84844

4.times isn't a closure exactly but a loop wrapper. With this statement You tell to execute 4 times a given closure. And a given closure in this case is the following piece of code:

{ counter ->
    task "task$counter" << {
        println "I'm task number $counter"
    }
}

It creates a task that has an argument passed (counter) in it's name. Is that clear?

Here You've docs for times method which is defined for Number class. As You can see You can invoke it on an instance of number and pass a closure. In this particular case a closure passed created a task.

Upvotes: 2

Related Questions