How to access `extensions` on any DSL object statically?

I’m trying to convert one of my plugins from Groovy to Kotlin and this is the last few lines of Groovy code in the project I cannot deal with:

class Utils {
    /**
     * Call {@code extensions} property on the object dynamically.
     */
    static ExtensionContainer getExtensions(Object obj) {
        return obj.extensions
    }
}

Currently I have a workaround in Kotlin to help usages from Kotlin:

/**
 * This should be `(this as dynamic).extensions as ExtensionContainer`, but `dynamic` is not allowed on JVM.
 * This version calls into Groovy so that Gradle's custom handlers (Decorated?) can respond correctly.
 */
internal val Any.extensions: ExtensionContainer get() = Utils.getExtensions(this)
// note: classpath for kotlinc is set up to see Groovy output so this is visible

I wonder how could I rewrite Any.extensions in pure Kotlin using statically typed public Groovy/Gradle APIs only.

An example usage:

import org.gradle.kotlin.dsl.getByName
val git: GITPluginExtension = project
	// this one is using org.gradle.api.Project.getExtensions()
	.extensions.getByName<VCSPluginExtension>("vcs")
	// using my extension property as written above
	.extensions.create("git", GITPluginExtension::class.java)

Hi Róbert,

The equivalent Kotlin extension would be:

val Any.extensions get() = (this as org.gradle.api.plugins.ExtensionAware).extensions

Kind regards,
Rodrigo

2 Likes

Thanks Rodrigo, works like a charm!
Such great pleasure to remove the last line of Groovy and apply plugin: 'groovy'.