overexchange
overexchange

Reputation: 1

apply() method syntax in groovy

In the below syntax:

plugins({
  id('application')
  id 'java'
  id('com.github.johnrengelman.shadow').version('4.0.1')
})
allprojects(
  {
    apply(plugin: 'application')
    apply(plugin: 'java')
    apply(plugin: 'com.github.johnrengelman.shadow')

    repositories({
      mavenCentral()
    })
  }
  ....

  task copyDeps(type: Copy) {
      from (configurations.runtime + configurations.testRuntime) exclude '*'
      into '/tmp'
  } 
)

my understanding is,

apply() method is passing key-value plugin: 'application', where key is plugin & value is 'application'

From the syntax aspect of apply() method, plugin: 'application' is not a readable syntax:

1) How do I understand this syntax apply(plugin: 'application')? Is plugin: 'application' an argument of type String passed through method apply()?

2)

Below syntax

task copyDeps(type: Copy) {  // Line 54
          from (configurations.runtime + configurations.testRuntime) exclude '*'
          into '/tmp'
      }

is written as

tasks.create('copyDeps', Copy, { 
                                from(configurations.runtime + configurations.testRuntime).exclude('*')
                                into(buildDir)
                                }
            )

but gives error:

FAILURE: Build failed with an exception.

* Where:
Build file '/home/../build.gradle' line: 54

?

Upvotes: 0

Views: 1358

Answers (1)

injecteer
injecteer

Reputation: 20699

This is an idiomatic groovy "shortcutting".

The line

apply(plugin: 'application')

can be rewritten as:

apply( [ plugin: 'application' ] )

and means, that the apply() method is called with a Groovy Map literal. Map literal replaces java's:

Map map = new HashMap();
map.put( "plugin", "application" );

If a method as the last argument accepts a map, the square brackets can be omitted.

The line can also be rewritten as:

apply plugin:'application'

with no brackets at all.

UPDATE:

2nd question:

yes it can (if it compiles). It looks ugly but valid.

In Groovy if method's last argument is a closure, it can be written either as

copyDeps( map ){ }

or

copyDeps map, {}

or (more javaish)

copyDeps( map, {} )

UPDATE 2:

tasks.create('copyDeps', Copy, {}) and task copyDeps(type: Copy) {} are also interchangeable this time in Gradle as per ref-doc.

The tasks.create() is a plain method call on a class property, whereas task copyDeps() represents another Groovy capability: the DSL Builders -> here Gradle DSL builder is used.

Upvotes: 2

Related Questions