Writing Clean Code is an art and there are some tools that help you to achieve, among those tools my favorite is ktlint. I would suggest whenever you are setting up a new project add this tool in your template.
Here are the steps:
project/build.gradle
apply plugin: "org.jlleitschuh.gradle.ktlint"
buildscript {
repositories {
...
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
...
//ktlint Plugin
classpath "org.jlleitschuh.gradle:ktlint-gradle:9.2.1"
}
}
subprojects {
apply plugin: "org.jlleitschuh.gradle.ktlint"
ktlint {
debug = true
}
}
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
kotlinOptions {
jvmTarget = "1.8"
}
}
ktlint {
android.set(true)
// debug.set(true)
// verbose.set(true)
outputToConsole.set(true)
outputColorName.set("RED")
// additionalEditorconfigFile = file(".editorconfig")
reporters {
customReporters {
register("html") {
fileExtension = "html"
dependency = "me.cassiano:ktlint-html-reporter:0.2.3"
}
}
}
filter {
exclude("**/build/**")
include("**/kotlin/**")
}
}
After syncing you can see these two task ktlintCheck
and ktlintFormat
in gradle
window
Use ktlint task in terminal
admin ~/Project$./gradlew ktlintCheck
This will check format issues in code, if you it can’t format/check then you have to do manually.
admin ~/Project$./gradlew ktlintFormat
This will auto format your code, if you it can’t then you have to do manually.
Use ktlint task in Android Studio
- Open Run->Edit Configuration
- Select your app -> Before launch
- Add Run Gradle Task by pressing + button
- Chose Project or app(Project:app) level to run ktlint
- Enter in Task: ktlintFormat .
You can see ktlintFormat
task in Before launch window
Now whenever you press Run button, ktlintFormat will run first don’t worry it will take few milliseconds and then app will run.
You can see issues in ktlintFormat window, if ktlint can’t format the file then it will print the issue description along with File and line number.
/../StringExt.kt:7:1: Wildcard import (cannot be auto-corrected)
/../Models.kt:1:1: class ModelB should be declared in a file named ModelB.kt (cannot be auto-corrected)
/../Models.kt:21:22: Not a valid Kotlin file (expecting a parameter declaration) (cannot be auto-corrected)
/../RvAdapter.kt:29:1: Unexpected indentation (7) (it should be 8)
For more info check Kotlin ktlint Plugin
For faq check Kotlin ktlint Plugin FAQ