Skip to content

Instantly share code, notes, and snippets.

@davidmerrick
Last active June 7, 2019 00:48
Show Gist options
  • Save davidmerrick/11d0dbf2b98e74cddc337990881bd098 to your computer and use it in GitHub Desktop.
Save davidmerrick/11d0dbf2b98e74cddc337990881bd098 to your computer and use it in GitHub Desktop.
Migrating to Gradle Kotlin DSL

Kotlin DSL for Gradle Intro

Why use this?

  • Build scripts and tooling written in Groovy are often hard to configure, hard to refactor, and non-idiomatic.
  • Type-safe build logic
    • IDE support
      • Code completion
      • Documentation
      • Refactoring
    • Fewer surprises at runtime
      • If you remove a plugin, like application, the IDE will notify you

Getting started

  • To use the Kotlin DSL, create a build.gradle.kts file instead of build.gradle
  • The settings.gradle file also moves to settings.gradle.kts
  • (kts extension is a Kotlin script handled by Kotlin scripting compiler, .gradle.kts is handled by Gradle and then passed to Kotlin scripting compiler)

Syntax changes

  • Most of the changes in converting from Gradle to Kotlin DSL boil down to syntax and making the build script as declarative as possible
  • Groovy strings can be quoted with single quotes 'string' or double quotes "string" whereas Kotlin requires double quotes "string"
  • Groovy allows for omission of parentheses when invoking functions whereas Kotlin always requires the parentheses Goovy:
implementation "com.twilio.sdk:twilio:7.17.0"

vs Kotlin:

implementation("com.twilio.sdk:twilio:7.17.0")
  • Kotlin always requires the assignment operator (to disambiguate between a function call and an assignment):
minSdkVersion = rootproject.minSdkVersion

vs Groovy:

minSdkVersion rootproject.minSdkVersion

Plugins block

The Kotlin Gradle DSL introduced a declarative plugins block, so the buildscript block is no longer needed.

plugins {
    `kotlin-dsl`
    id("com.android.application")
    kotlin("android")
    kotlin("android.extensions")
    kotlin("kapt")
}

Two options here:

  • id() for generic plugins
  • kotlin() for Kotlin plugins

Note that this is much more declarative syntax than the imperative apply plugin in Groovy:

apply plugin: 'java'
apply plugin: 'jacoco'
apply plugin: 'org.springframework.boot'

Performance

It's recommended to make use of the Gradle build cache. Kotlin 1.2.21 allows Kotlin projects to make use of build caching.

Two ways to enable it:

  • Current build only: --build-cache flag on the command-line.
  • Project level: add org.gradle.caching=true to $PROJECT_ROOT/gradle.properties.

To populate the cache: ./gradlew assemble --build-cache

Tooling

Useful plugin: https://github.com/jmfayard/buildSrcVersions

Generates constants for libs and versions used in your build, places them in buildSrc. Checks for new versions of dependencies.

Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment