Freelancing for Pale Blue

Looking for flexible work opportunities that fit your schedule?


Keep Your Kotlin Code Spotless: A Guide to ktlint and ktfmt Linters

Android Jan 12, 2024

In the bustling world of Kotlin/Android development, maintaining code quality and consistency is essential. This is where linters come in, like shining knights cleaning up and polishing your codebase. But with a variety of linters available, each addressing different aspects, choosing the right ones can be like picking the perfect weapons for your coding quest.

In this blog post, we'll delve into the realms of two popular Kotlin/Android linters: ktlint and ktfmt, dissecting their strengths and helping you decide which one best suit your coding needs.

The Formatting Enforcer: ktlint

Imagine ktlint as your meticulous code formatting companion. Developed by the team at Pinterest, it acts as a powerful style checker and formatter for your Kotlin projects. Its primary mission? To enforce consistent code formatting and style conventions, ensuring your code shines with uniformity.

Think of ktlint as a strict but helpful teacher, meticulously focusing on aspects such as code formatting. Here's what makes it special:

  • Customizable Styles: Create your ideal code aesthetic with a personalized .editorconfig file.
  • Precise Enforcement: Say goodbye to inconsistencies! ktlint identifies formatting violations and guides you towards clean, consistent code.
  • Flexible Integration: Adapt ktlint to your workflow, run it on-demand, integrate it into your IDE, or automate it for continuous code hygiene.

But the best part? ktlint is customizable! You can choose which coding standards you want to enforce, tailoring it to your specific project needs and preferences. Think of it as fine-tuning your formatting preferences!

Integrating ktlint in kotlin gradle project

  • In the project's root build.gradle.kts file, apply the ktlint-gradle plugin:
plugins {
    // Get the current version from https://github.com/JLLeitschuh/ktlint-gradle
    id("org.jlleitschuh.gradle.ktlint") version "<current_version>" apply false
}
  • Add the following in the project's root build.gradle.kts file to apply ktlint plugin to all project modules
subprojects {
    apply(plugin = "org.jlleitschuh.gradle.ktlint")

    // Optionally configure plugin
    configure<org.jlleitschuh.gradle.ktlint.KtlintExtension> {
        debug.set(true)
    }
}
  • Although ktlint comes with robust default formatting rules, it also grants you the ability to tailor your code to match your individual preferences. To explore the extensive customization options, create a .editorconfig file in your project's root directory, and  add ktlint rules documentation available at https://pinterest.github.io/ktlint/latest/rules/code-styles/.

Example configuration file

[*.{kt,kts}]
max_line_length = 120 #enforce a maximum line length of 120 characters
indent_size = 4 #use 4 spaces for indentation

With ktlint prepped, let's see it in action! Run the following Gradle tasks to experience the transformation:

  • ./gradlew ktlintCheck: Checks your code for formatting errors, but leaves it untouched.
  • ./gradlew ktlintFormat: Applies ktlint's magic touch, automatically formatting your code according to the rules specified in .editorconfig.

The Opinionated Maestro: ktfmt

Now, meet ktfmt, the opinionated maestro of Kotlin formatting. Developed by Facebook (Meta), it takes a different approach. Instead of offering customization, ktfmt proudly wears its "one size fits all" hat. It simply applies its own, well-defined set of formatting rules, regardless of your initial code's appearance.

Think of ktfmt as a skilled artist, taking your code as raw material and transforming it into a beautifully formatted masterpiece. Here's what makes it special:

  • Deterministic results: No matter how messy your code starts, ktfmt will always produce the same consistent output. This predictability offers peace of mind, knowing your code will always be formatted in a specific, well-defined style.
  • Focus on the essence: By taking formatting off your plate, ktfmt frees you to focus on the bigger picture – the logic and functionality of your code. No more wasting time battling indentation or spacing!
  • Simplicity and ease of use: ktfmt is straightforward to use. Just integrate it into your workflow, and let it work its magic behind the scenes. No need for extensive configuration or customization.

Of course, this "one size fits all" approach might not appeal to everyone. If you prefer more control over formatting, ktlint might be a better choice. But for those who value simplicity and predictability, ktfmt is a powerful tool to keep your code consistently formatted.

Integrating Ktfmt in kotlin gradle project

  • In the project's root build.gradle.kts file, apply the ktfmt-gradle plugin:
plugins {
    // Get the current version from https://github.com/cortinico/ktfmt-gradle
    id("com.ncorti.ktfmt.gradle") version "<current_version>" apply false
}
  • Add the following in the project's root build.gradle.kts file to apply ktfmt gradle plugin to all project modules
subprojects {
    apply(plugin = "com.ncorti.ktfmt.gradle")

    // Optionally configure plugin
    configure<com.ncorti.ktfmt.gradle.KtfmtExtension> {
        kotlinLangStyle()
    }
}

With ktfmt prepped, let's see it in action! Run the following Gradle tasks to experience the transformation:

  • ./gradlew ktfmtCheck: Checks your code for formatting errors, but leaves it untouched.
  • ./gradlew ktfmtFormat: Applies ktfmt's automated code formatting in a deterministic manner, ensuring consistent and predictable code formatting throughout your project.

PS: The above-mentioned Gradle plugins for ktlint and ktfmt are community-maintained and not official. However, it's worth noting that the maintainers of ktlint and ktfmt have explicitly mentioned these plugins for setting up these linters. For alternative methods or more detailed setup instructions, it is recommended to check their respective webpages.

Tags

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.