Android project code style using Spotless and ktlint

Why?

When you write code, it’s always good to follow some common code style. But doing this manually, even using modern IDEs like Android Studio is painful — sooner or later you’ll forget about this.

How to solve the problem?

  • No semicolons (unless used to separate multiple statements on the same line)
  • No unused imports
  • No consecutive blank lines
  • No blank lines before }
  • etc

Project integration

classpath ‘com.diffplug.spotless:spotless-plugin-gradle:3.27.0’
buildscript {

repositories {
google()
jcenter()

} dependencies {
classpath "com.android.tools.build:gradle:4.0.0-alpha07"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.diffplug.spotless:spotless-plugin-gradle:3.27.0'
}
}

allprojects {
repositories {
google()
jcenter()
}
}
apply plugin: "com.diffplug.gradle.spotless"

spotless {
java {
target '**/*.java'
googleJavaFormat().aosp()
removeUnusedImports()
trimTrailingWhitespace()
indentWithSpaces()
endWithNewline()
}
kotlin {
target '**/*.kt'
ktlint()
trimTrailingWhitespace()
indentWithSpaces()
endWithNewline()
}
format 'misc', {
target '**/*.gradle', '**/*.md', '**/.gitignore'
indentWithSpaces()
trimTrailingWhitespace()
endWithNewline()
}

format 'xml', {
target '**/*.xml'
indentWithSpaces()
trimTrailingWhitespace()
endWithNewline()
}
}
googleJavaFormat().aosp()
removeUnusedImports()
trimTrailingWhitespace()
indentWithSpaces()
endWithNewline()
apply from: “$project.rootDir/spotless.gradle”
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'

apply from: "$project.rootDir/spotless.gradle"// ....

Troubleshooting

Gradle probably will raise this error during the synchronization:

Cannot add task ‘clean’ as a task with that name already exists
task clean(type: Delete) {
delete rootProject.buildDir
}

Setting up Android Studio

We have to change some settings in Android Studio to make it format code the right way.

$ brew install ktlint
$ ktlint --android applyToIDEAProject
Java settings
Kotlin settings

Using Spotless

./gradlew spotlessCheck
./gradlew spotlessApply

Bonus: Travis CI integration

script:
— “./gradlew spotlessCheck”
— “./gradlew :library:clean :library:build :library:connectedCheck -PdisablePreDex — stacktrace”
— “./gradlew :app:clean :app:build :app:connectedCheck -PdisablePreDex — stacktrace”

Source code

You can find the full integration in the real project in this repository.

Senior Android Engineer