Android code style using Spotless and Ktlint

1 minute read

Code Style is Guidelines for developers

We have a lot of code styles in the Kotlin world. Android has its own code style guide. Kotlin also has its own code conventions.

Spotless will help us! It allows us to format and check rules code in multiple languages. If you’re an Android developer with Kotlin or Java Language. Spotless is the solution for you. Because they have ktlint for kotlin and for Java is google java format, and etc.

Let’s setup it

First of all, add the following dependency to your project-level build.gradle:

1classpath 'com.diffplug.spotless:spotless-plugin-gradle:5.15.0'

Second, create a file spotless.gradle at root project, make sure the latest version of ktlint

 1apply plugin: "com.diffplug.spotless"
 2spotless {
 3    java {
 4        target '**/*.java'
 5    }
 6    kotlin {
 7        target "**/*.kt"
 8        ktlint('0.43.2').userData([
 9                'max_line_length': '150',
10                'disabled_rules' : 'no-wildcard-imports'
11                ]) 
12    }
13    format 'misc', {
14        target '**/*.gradle', '**/*.md', '**/.gitignore'
15    }
16    format 'xml', {
17        target '**/*.xml'
18    } 
19}

Finally, the config above can apply to all project modules. Copy code below to your project-level build.gradle

1subprojects {
2    afterEvaluate { project ->
3        project.apply from: '../spotless.gradle'
4    }
5}

Using Spotless

Using Spotless is even easier than setting up. We need two commands:

The first is checking the code style. If there is a problem it fails with an error.

1./gradlew spotlessCheck

The second is auto-formats the code. Fix formatting issues in the whole project calling it. It is only for formatting the code. However, it can’t fix issues like wildcard imports. You have to fix them manually.

1./gradlew spotlessApply

Setting up in the Android Studio

We change the android studio format code style, following project code style. First of all, Install Ktlint on your local computer. the example using macOS:

1brew install ktlint

Next, navigate to your project’s directory in the terminal and execute this command:

1ktlint --android applyToIDEAProject