Skip to content
DeveloperMemos

Adding ktlint to an Android Project

Kotlin, Android1 min read

If you want something to analyze your Kotlin code ktlint does the job pretty well. Unfortunately the documentation isn't that clear about how to set everything up. Here's a really quick rundown.

Adding klint to your Android Project

First create a new file in your project root called 'ktlint.gradle' and put this in it:

1repositories {
2 jcenter()
3}
4
5configurations {
6 ktlint
7}
8
9dependencies {
10 ktlint "com.github.shyiko:ktlint:0.31.0"
11 // additional 3rd party ruleset(s) can be specified here
12 // just add them to the classpath (ktlint 'groupId:artifactId:version') and
13 // ktlint will pick them up
14}
15
16task ktlint(type: JavaExec, group: "verification") {
17 description = "Check Kotlin code style."
18 main = "com.github.shyiko.ktlint.Main"
19 classpath = configurations.ktlint
20 args "src/**/*.kt"
21 // to generate report in checkstyle format prepend following args:
22 // "--reporter=plain", "--reporter=checkstyle,output=${buildDir}/ktlint.xml"
23 // see https://github.com/pinterest/ktlint#usage for more
24}
25check.dependsOn ktlint
26
27task ktlintFormat(type: JavaExec, group: "formatting") {
28 description = "Fix Kotlin code style deviations."
29 main = "com.pinterest.ktlint.Main"
30 classpath = configurations.ktlint
31 args "-F", "src/**/*.kt"
32}

After that open up your app-level build.gradle file and add the following line:

1apply from: "../ktlint.gradle"

This goes nicely under any other 'apply plugin's you already have in there. So for example:

1apply plugin: 'com.android.application'
2apply plugin: 'kotlin-android'
3apply plugin: 'kotlin-android-extensions'
4apply plugin: 'io.fabric'
5
6apply from: "../ktlint.gradle"
7
8android {
9 ...

It should ask you to sync your project, after that is done you can use the following command to run ktlint:

1./gradlew ktlint

Happy linting!