Improve your Kotlin code with Detekt

Jordan Gout
FrichtiTech
Published in
3 min readOct 11, 2021

--

As a developer you have your own coding style and keeping a codebase both consistent and maintainable in a project with multiple developers can be challenging.

During a code review, you want to focus on business logic, algorithmic, coding patterns and not on code styling, on variable naming, this is why you should use linters.

This article will focus on Detekt, a static code analysis tool for Kotlin.

Detekt comes with multiple rules sets like style, complexity, naming, and others and allowed to easily create you own rules.

Add Detekt to your project

Note : On this article, code sample will used Gradle Kotlin DSL on a multi modules android project

You need to add Detekt dependency to you buildSrc gradle file :

You can use Detekt’s default task like ./gradlew detekt but on this exemple I want to run Detekt only once on multiple modules. I need to create a plugin to define custom tasks and settings:

In the code snippet above, we are setting the source directory of the project (projectDir), then we are defining two glob filters to run Detekt on all .kt and .kts files and finally we are ignoring the resources and the build folders

Finally, you need to enable the Detekt plugin on the gradle’s file at the root of your project:

Apply custom your Detekt plugin to project

Configure Detekt’s rules

Now you need to select rules you want to apply to your project. You can either use buildUponDefaultConfig property or create your own config file.

Check Detekt docs to create your own config file.

Let’s run Detekt

Now Detekt is ready, but you may have some issues as above. In that case you can choose to fix them all but what if you can’t right now or what if your project is already in production and you have a couple hundred issues?

You can use @Supress annotation to ignore a single issue. You should use this option in the worst case only. To ignore existing issues you should use baseline.

Create baseline file to ignore legacy issues

We need to modify our Detekt plugin:

Now we need to run ./gradlew detektAllBaseline to ask Detekt to create our baseline file.

Let’s retry to run ./gradlew detektAll task.

All existing issues are now ignored so you can focus on new development and takes time to remove thoses previous issues.

Going further

--

--