DEV Community

Cover image for Adding Klint to my Android apps
Jess Barrientos
Jess Barrientos

Posted on • Edited on

Adding Klint to my Android apps

First of all, what is ktlint ❤️?

As it's documentation says:

ktlint is an anti-bikeshedding Kotlin linter with built-in formatter.

Basically, is a code analysis tool for Kotlin, maintain by Pinterest.

I find this tool easy to integrate to any Android project and also easy to maintain. Let's go to the point and start with the configuration.

First we need to create a new gradle file in my case I'm going to name it: ktlint.gradle, no need to overthink the name, but you can name it whatever you want. Place it at the same level of your build.gradle(:app) and paste the next content:

configurations {
    ktlint
}

dependencies {
    ktlint "com.pinterest:ktlint:0.44.0"
}
task ktlint(type: JavaExec, group: "verification") {
    description = "Check Kotlin code style."
    main = "com.pinterest.ktlint.Main"
    classpath = configurations.ktlint
    args "src/**/*.kt"
}

check.dependsOn ktlint

task ktlintFormat(type: JavaExec, group: "formatting") {
    description = "Fix Kotlin code style deviations."
    main = "com.pinterest.ktlint.Main"
    classpath = configurations.ktlint
    args "-F", "src/**/*.kt"
}

Enter fullscreen mode Exit fullscreen mode

First, we can see on the dependencies section the last version available of ktlitn: as today is com.pinterest:ktlint:0.44.0.

Then, we can see two gradle tasks ktlint and ktlintFormat. The first task ktlint is going to check your kotlin code and report any style issue. The second task ktlintFormat is going to fix any kotlin code style by its own.

Now, we need to add our file to our gradle scrip modules so, let go to the build.gradle(:app) aand let's add it in the plug-in section. e.g.


plugins {
   .... 
}

apply plugin: "kotlin-kapt"
apply plugin: "dagger.hilt.android.plugin"
apply plugin: "androidx.navigation.safeargs.kotlin"
apply from: "../ktlint.gradle"


android {
....
}
Enter fullscreen mode Exit fullscreen mode

And don't forget to Sync your project!

How can I run it ?

To make it work, just run the commands or tasks in the terminal.

./gradlew ktlint
Enter fullscreen mode Exit fullscreen mode

or

./gradlew ktlintFormat
Enter fullscreen mode Exit fullscreen mode

And that's it, Hope you find it helpful!

Refs.
Klint Page
Klint Github

Top comments (0)