Code styling for Kotlin
This article helps you to implement Code style check for Kotlin.
Have you tried implementing code style check for kotlin?
Okay!! Lets go back, I mean Java!!!
There are many for java: findbugs, pmd , checkstyle, SonarQube.
For Example:
Then we add the checkstyle.xml and suppression.xml to their respective path specified, which will contain rules and after that we run checkstyle
./gradlew checkstyle
Unfortunately, Checkstyle doesn't support kotlin files, It only generates report for java files.
How did I achieve it for kotlin?
I was able to find two meaningful options:
1. Detekt — https://github.com/arturbosch/detekt
2. ktlint — https://github.com/shyiko/ktlint
I personally don’t prefer Ktlint since its rules are not customisable, on the other hand, Detekt, works pretty fine and customisable, though the plugin integration seems new.
Implemenation
Add the following in your build.gradle(root project).
Ideally, We should be adding this in the root project and selectively apply the plugin in submodules, but this does not work properly with Detekt in Android yet, so we have to manually add the plugin to build.gradle of root project.
`input` is path for the directory where detect will start checking.
Before running detektCheck, Run detektGenerateConfig
./gradlew detektGenerateConfig
Why??
detektGenerateConfig will generate the default-detekt-config.yml file with defaults rules.
Oh yeah!!!!! There are many things.
I will point out some rules which I felt important.
1.maxIssues - Threshold for maximum errors.
2.empty-blocks: catch, constructors, if , else blocks.
3.exceptions - TooGenericExceptionThrown etc.
4.naming conventions, Unused imports, Unnecessary use of wild imports.
Customise according to your needs and………….!
You are good to go!!!
Run
./gradlew detektCheck
Sample Output
That is it……!!
Reference: https://github.com/arturbosch/detekt
Please don’t forget to clap, if you find this article helpful.
Thanks!!