Android project code style using Spotless and ktlint

Why?

How to solve the problem?

  • 4 spaces for indentation
  • 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

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

Setting up Android Studio

$ 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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store