Migrating to Gradle Kotlin DSL

A Step by Step Guide

Tom Hanley

Senior Software Engineer @

Organiser of the Dublin Kotlin User Group

Huge fan of Kotlin

What is Gradle?

General purpose build management system

Gradle Creation

  • They chose Groovy over Java because:
    • It could provide an extensible DSL
      • Highly declarative builds
  • Didn't realise the limitations around tooling
    • Due to Groovys dynamic types and metaprogramming, tooling is hard
    • Bad user experience
      • Hard to configure and refactor

Gradle Kotlin DSL

  • From Hans Dockter, the creator of Gradle

    • "Kotlin is better than groovy"

    • "I wish Kotlin existed when I created Gradle"

    • "You lucky b*******s"

Gradle Kotlin DSL

  • Why switch to the Gradle Kotlin DSL?
    • Better developer experience
      • Type safe build logic
      • Great IDE Support
        • Shorter feedback loop
        • Way more compile time checks
        • Find usages, refactoring support
    • Groovys dynamism has performance hit
    • Null Safety
    • Documentation + discovery

Gradle Kotlin DSL

  • Shipped as part of Gradle 5.0
  • Kotlin + groovy can live side by side
    • Due to groovy dynamism
    • Kotlin should drive groovy, not the opposite

Migration Demo

Migration Prep

  1. Prepare all gradle scripts:
    1. Use replace ' with "
    2. Disambiguate function calls and property assignments
    3. Use plugins block
    4. Make sure everything still compiles

 

Shared code

 

  1. Create the buildSrc folder

    1. Create the src/main/kotlin directory

    2. Create the build.gradle.kts file

      1. Plugins block with `kotlin-dsl` applied

      2. Repositories block with jcenter()

    3. Create Dependencies.kt file

    4. Make sure everything compiles

The Real Migration

  1. Rename scripts to .gradle.kts
    1. settings.gradle
    2. build.gradle
    3. app/build.gradle
  2. Fix issues
    1. Where the bulk of the time is spent

The Issues

  1. build.gradle

    1. compileSdkVersion

    2. isEnabled

    3. Release

      1. getByName

    4. isMinifyEnabled

    5. kotlinOptions

      1. https://github.com/gradle/kotlin-dsl-samples/issues/1368

Migration 3

  1. remove libraries namespace

    1. issue with list of dependencies

      1. Create extension functions

    2. Test logging fix

      1. Refactor- extract function

  2. Delete dependencies.gradle file

Key Takeaways

  • The migration can be tricky
    • No auto convert from groovy to kotlin
    • Differences in Kotlin and Gradle APIs.
    • You don't get much IDE feedback when scripts aren't compiling
  • Its worth it in the end, it'll make your life easier

Coming up

are hiring!

Thank you!

Questions?

Twitter: @conduct_of_code

Linkedin: Tomás Hanley
Medium: @hanleyt
 

Migrating to Gradle Kotlin DSL

By Tom Hanley

Migrating to Gradle Kotlin DSL

  • 478