According to their Github repo, KTLint is An anti-bikeshedding Kotlin linter with a built-in formatter. They have explained it well how to integrate it into your Android project, however, in this document, I would like to say how to integrate it into your build process and reformat the style of everyone in the team to the standard style.
Medium has a problem with parse and display of code under one gist file. This is the link to my gist on Github. Please refer to this link if there is any problem.
Create files
We need to create two new files. The first one is ktlint.gradle file and the second one is pre-commit.
- I prefer to put my .gradle files under the gradle folder at the root of the project. So, create a file under this folder and name it ktlint.gradle.
2. I prefer to put my scripts under the scripts folder at the root of the project. So, create this folder if you don’t already have one at the root and then create a pre-commit file under it. Note: Make sure to don’t add any type to it, such as .sh, otherwise you git system ignores it.
Adding them to the Gradle build system
3. Create tasks.gradle file and under the gradle folder (as mentioned in step 1) and copy/paste the following lines in it.
What is installGitHook task? pre-commit file is not part of the project. It is part of the git pre-hook system. In order to install it for every developer, we keep a copy of that under version-control in our code base and copy it to its proper destination.
What does it do? This script will be run when the developer commits something. It runs the ktlint task first and receives the result. If something is wrong then it fails the commit.
Ask the app module to use it
We want to above tasks to be run whenever the developer builds the app. So, by one line of the code, we are able to run the above tasks.
4. Open the build.gradle file of your app module and apply the tasks.gradle file.
Now, what?
The developer changes the codebase (by fixing a bug or adding a feature), he is done and commits his change. pre-commit hook will be called by the git and this script runs the ktlint task. If there is no problem and ktlint is happy with the change then commit will be placed and the developer is able to push the change to upstream. If the commit fails (means ktlint tried to fix it but couldn’t), then you can go to your terminal and run the ktlintFormat task using this command.
./gradlew ktlintFormatIt will tell you what is the problem. The output will be something like this (Note: I named ktlintFormat task in my project afs_ktlintFormat. So, they are the same thing).

Thanks for reading this article. If you like this article, please hit the ♥ and share it with your friends.
