Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use plugins.withType(somePlugin).whenPluginAdded

A gradle build has several submodules. Some of them have the java plugin applied, some don't. I'm trying to configure the plugin only when it's applied. To do this, I add the following in my top-level build.gradle file:

allprojects {
  plugins.withType(JavaPlugin) {
    //some configuration on the JavaPlugin
  }
}

However, I also noticed the following style:

allprojects {
  plugins.withType(JavaPlugin).whenPluginAdded {
    //some configuration on the JavaPlugin
  }
}

What's the difference between the 2. When do I use the withType(){}-style configuration and when do I use the withType().whenPluginAdded{}-style?

like image 267
Jan Bols Avatar asked Aug 31 '25 03:08

Jan Bols


1 Answers

When you use whenPluginAdded() it invokes whenObjectAdded() on the current collection. And when you call withType() and pass a Closure, it invokes all() on the current collection, which in its turn calls whenObjectAdded() on a copied collection.

So both these methods do the same thing but the former makes a defensive copy of a plugin collection.

like image 87
Michael Avatar answered Sep 02 '25 20:09

Michael