gradle / kotlin-dsl-samples

Samples builds using the Gradle Kotlin DSL
https://gradle.org/kotlin/
Other
3.71k stars 434 forks source link

How to use closures? #1408

Open antonalechnovic opened 4 years ago

antonalechnovic commented 4 years ago

I am trying to convert the following groovy snippet to Kotlin:

class CustomPlugin implements Plugin<Project> {
    void apply(Project target) {
        target.apply plugin: 'com.jfrog.artifactory'
        target.artifactory {
            contextUrl = "http://some/artifactory/"
        }

}

How to set target.artifactory.contextUrl and remaining parameters?

I want to configure simillarly to build.gradle :

artifactory {
   contextUrl ="someUrl"
    publish {
        repository {
            repoKey = "some"
            username = "someUsername"
            password = "somePassword"
        }
}
StefMa commented 4 years ago

You can apply the plugin with the PluginManager. You can get an instance from it from the Project.

The "closure" is an Gradle extension. Get an instance of it with project.extensions.getByType(ClassOfTheExtension::java:class). You can simply set the properties on it.

The class of the extension can be find somewhere in the source code of the applied plugin.

JLLeitschuh commented 4 years ago

There are also some examples here: https://docs.gradle.org/current/userguide/kotlin_dsl.html#groovy_closures_from_kotlin