How does gradle merge extensions?

Hello!

I can have a set some extension properties on the root project (using plugins.withType for exampe) and then define additional properties on the project itself and graldle will happily merge them all. Does anyone know how this is done? I tried navigating the source but with no success…

Thanks!

Necro, but since this is still the top result when searching, it should have an answer.

“Extension” classes are automagically turned into “ExtensionAware” instances, which are arbitrary objects that can themselves be extended. The “idea-ext” plugin uses this to make itself configurable through Gradle’s own “project.idea { }” block: gradle-idea-ext-plugin/src/main/groovy/org/jetbrains/gradle/ext/IdeaExtPlugin.groovy at 52bdbbd1c3d9bd46d27596d3072f5d7a450721de · JetBrains/gradle-idea-ext-plugin · GitHub

Essentially, you cast the existing extension to ExtensionAware, allowing you to add your own sub-extensions to the original extension.

Unfortunately, your post is neither correct, not relevant to the thread and the question OP asked.

You mix up two orthogonal things. Anything you let Gradle create is decorated with things like injecting services and being ExtensionAware whether you declare it or not. This you should imho always let Gradle instantiate things and also explicitly declare implementing ExtensionAware, then you don’t need a cast to add extensions to it. These things are true, no matter how the created instance is used.

As at the same time, just because sometime is added as extension does not mean, that it has the Gradle decorations like ExtensionAware. You can create an object by calling a constructor and add it as extension. This will then not be ExtensionAware itself. But I would usually not recommend to do that in most situations.

Also, the original question of this task is totally different. And the answer to that is, that there is nothing “merged”. The configuration happens single-threaded sequentially. If you have two places configuring one extension, the second place gets the same instance where the first place already did its configuration changes on.

And besides that, the mentioned plugins.withType should not be used. (see the JavaDoc of getPlugins) Instead for example pluginManager.withPlugin should be used to react to a plugin being applied.