Search code examples
kotlingradlebuild.gradlegradle-kotlin-dsl

Converting Groovy tasks build.gradle to kotlin kts file


I am trying to convert my build.gradle file in Groovy to a kotlin .kts file, I have some tasks in the gradle file that I dont know how to convert correctly

task androidJavadocs(type: Javadoc) {
    failOnError = false
    source = android.sourceSets.main.java.srcDirs
    ext.androidJar = "${android.sdkDirectory}/platforms/${android.compileSdkVersion}/android.jar"
    classpath += files(ext.androidJar)
    exclude '**/R.html', '**/R.*.html', '**/index.html'
}

task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) {
    classifier = 'javadoc'
    from androidJavadocs.destinationDir
}

I dont quite understand how to use the "type", I was going down this path

val androidJavadocs by tasks.withType<Javadoc>(){

}

but its giving me the error

Type 'DomainObjectCollection<Javadoc!>' has no method 'getValue(Build_gradle, KProperty<*>)' and thus it cannot serve as a delegate

How do I convert those groovy tasks to kotlin tasks correctly?


Solution

  • You can use the named() method to configure existing tasks and the register() method to create new ones.

    tasks {
        register<Javadoc>("androidJavadocs") {
            // Task's body here
        }
    }
    
    // or
    
    tasks.register<Javadoc>("androidJavadocs") {
        // Task's body here
    }
    
    

    If you want to use Kotlin delegated properties

    val androidJavadocs by tasks.registering(Javadoc::class) {
        // Task's body here
    }
    

    The full answer to your question

    val androidJavadocs by tasks.registering(Javadoc::class) {
        isFailOnError = false
        source = android.sourceSets.main.java.srcDirs
        ext["androidJar"] = "${android.sdkDirectory}/platforms/${android.compileSdkVersion}/android.jar")
        classpath += files(ext["androidJar"])
        exclude("**/R.html", "**/R.*.html", "**/index.html")
    }
    
    val androidJavadocsJar by tasks.registering(Jar::class) {
        classifier = "javadoc"
        dependsOn(androidJavadocs)
        from(androidJavadocs.get().destinationDir)
    }