How to setup ktlint for your project in android
Introduction: Ktlint is a formatting tool which is used to maintain a standardization in code across the project.
Why to use it: Spending time on configuration (& maintenance down the road) of hundred-line long style config file(s) is counter-productive. Instead of wasting your energy on something that has no business value — focus on what really matters (not debating whether to use tabs or spaces).
How it helps: Maintaining a quality code when multiple people are working on the project, If forces certain checks such as extra line, spacing, removing wild card imports, semicolons, no tailing white spaces, no unit returns, no empty class bodies, etc..
Configuring in Mac:
Installing Ktlint locally in system
Git hook not to allow pushing with lint errors
Run KtLint on all the kotlin files in the src folder
Auto correcting style violations, If some errors cannot be fixed, They will be printed
Configuring in Windows:
Adding the git pre-commit hook
- Make sure you have added java in the environment variable Path, test this by running java -version in cmd/PowerShell
- Go to the mobile project directory → Navigate to .git/hooks/ folder
- Create a file called pre-commit ( there’s no extension )
- Add the following code to the file and save the file
Configuring in Android Studio:
- Go to Android Studio → Preferences/Settings → Editor
- General → Auto Import → check Optimize imports on the fly (for current project)
- Navigate into: Code Style → Kotlin
- Set from… (Link on the right side) → Predefined style → Kotlin style guide (Kotlin plugin 1.2.20+)
- Open Code Generation tab → uncheck Line comment at first column
- In Code Generation tab → select → Add a space at comment start.
- Open Imports tab → select → Use single name import (all of them)
- Then, Remove import java.util.* from Package. (Not just uncheck, you should remove it)
- Then, Remove import kotlinx.android.synthetic.* from Package. (Not just uncheck, you should remove it)
- Open Blank Lines tab → change Keep Maximum Blank Lines / In declarations & In code to 1 and Before ‘}’ to 0.
- Open Wrapping and Braces tab → uncheck Function declaration parameters → Align when multiline.
- Open Tabs and Indents tab → change Continuation indent to the same value as Indent (4 by default).
- Inspections → Kotlin → Redundant Constructs → change Severity level of Unused import directive and Redundant semicolon to ERROR.
Shortcuts to run format (On Mac):
- Run format on a file → Command + Option + L
- Run format on a section of code → Select the part of the code you want to format and do Command + Option + L
- Run format on all files in folder → Right click on the folder and select “Reformat code“ or do Command + Option + L
Useful Resources: