[Note] Gradle Kotlin DSL

·

2 min read

Intro

Normally Gradle uses Groovy as DSL. There is also a Kotlin DSL often used in Kotlin projects. docs.gradle.org/current/userguide/kotlin_ds.. docs.gradle.org/current/userguide/migrating..

Why?

  • Use the same syntax as Application
  • static-typed. So works well with existing IDEs like Intellij

Tips

  • Check official documentations about the block type / return type
  • Check the block's class name in Intellij
  • Define in root file, then check class name in Intellij. Then move to Configure / WithType syntax in sub-files
  • Write in Groovy first, then check the class name in Intellij

Type-safe model accessors

Example: SourceSets

Type-safe model accessors, similar to Groovy DSL:

sourceSets {
    main {
        java {
            setSrcDirs(listOf("src"))
        }
    }

    test {
        java {
            setSrcDirs(listOf("test"))
        }
    }
}

Check document:

This is defined by SourceSetContainer docs.gradle.org/current/dsl/org.gradle.api... docs.gradle.org/current/javadoc/org/gradle/.. gradle.github.io/kotlin-dsl-docs/api/org.gr..

Configure Without Type-safe Model Accessors

in files not in root project or file included..etc

docs.gradle.org/current/userguide/kotlin_ds..

// Example from official guide
apply(plugin = "java-library")

dependencies {
    "api"("junit:junit:4.13")
    "implementation"("junit:junit:4.13")
    "testImplementation"("junit:junit:4.13")
}

configurations {
    "implementation" {
        resolutionStrategy.failOnVersionConflict()
    }
}

configure<SourceSetContainer> {
    named("main") {
        java.srcDir("src/core/java")
    }
}

configure<JavaPluginConvention> {
    sourceCompatibility = JavaVersion.VERSION_11
    targetCompatibility = JavaVersion.VERSION_11
}

tasks {
    named<Test>("test") {
        testLogging.showExceptions = true
    }
}

Snippets

// register a new test task
register<Test>("functionalTest")) {
}
// configure all tasks with type Test
withType<Test> {
}
// get task from another task
project.tasks.getByName<Test>("functionalTest")