I am writing a Gradle plugin in Kotlin language using kotlin-dsl plugin:
plugins {
`kotlin-dsl`
}
I have created a plugin class and an extension:
class MyPlugin : Plugin<Project> {
private lateinit var extension: MyPluginExtension
override fun apply(project: Project) {
extension = project.extensions.create("myPluginExtension")
...
}
}
There is an infix function foo inside my extension class:
open class MyPluginExtension {
infix fun String.foo(other: String) {
...
}
}
Here is how plugin users are supposed to use my plugin (using Kotlin DSL):
plugins {
id("my-plugin")
}
myPluginExtension {
"first" foo "second"
}
I want to have the same syntax for plugin users that use Groovy language:
myPluginExtension {
'first' foo 'second' // cannot call Kotlin infix function using Groovy
'first'.foo('second') // this is not working too
foo('first', 'second') // ok, but not desired syntax for me
}
I don't know Groovy much, but I've heard it has extension methods. How to make my plugin looks cool for Groovy lovers?
If it is not possible to make a function call directly, I believe there is a way to create a wrapper extension method in Groovy language that will call the Kotlin extension function.
I've found a similar question Kotlin function parameter with receiver, called from Groovy, but it is not exactly what I need.
i'm not familiar with kotlin, so, i'll be referencing java as a baseline
here is an extension method for
Stringclass in groovy world:in java you can use approximately this code to register extension method for some class:
PS: it's still possible to achieve syntax
"aaa" foo "bbb"groovy will translate this line to approximately following code:
as soon as "aaa" is dynamic - you can implement GroovyObect invokeMethod in your plugin that will be invoked on any unknown method call
this approach is quite tricky but doable. i'm lazy to implement it in java. here is a groovy code that you can run in groovy console: