← Back to list

Supercharge Your Kotlin Codebase with Detekt: Integration + Custom Rules

When working on large Kotlin projects, maintaining code quality, readability, and consistency becomes non-negotiable. That’s where Detekt…

Richa Shah · 2025-07-30 10:38 · 0 claps · 2.3 min read
#android #android-app-development #lint #mobile-app-development #coding-standards
Open on Medium ↗
Wiki topics: 💻 · Programming 📱 · Mobile Development

Supercharge Your Kotlin Codebase with Detekt: Integration + Custom Rules

When working on large Kotlin projects, maintaining code quality, readability, and consistency becomes non-negotiable. That’s where Detekt comes in.

Detekt is a powerful static code analysis tool for Kotlin that helps you detect code smells, enforce coding standards, and keep your project clean — just like Lint does for XML and Java, but tailored for Kotlin.

In this post, we’ll walk through:

  • What Detekt is and why it’s helpful
  • How to integrate Detekt into an Android project
  • How to configure and run Detekt
  • How to write custom Detekt rules to enforce project-specific standards
  • How to test and use your custom rule in production

🔍 What is Detekt?

“Static code analysis for Kotlin.” — Detekt GitHub

Detekt scans your codebase for:

  • Complexity
  • Naming issues
  • Bad practices
  • Potential bugs
  • Style violations
  • …and more

Unlike Javadoc or Checkstyle, Detekt was built for Kotlin from the ground up. It offers out-of-the-box rule sets and allows custom rules, baseline support, IDE integration, and CI/CD integration via GitHub Actions, SonarQube, and more.

🛠️ Step-by-Step Integration in Android Studio

1. Add Detekt to build.gradle

Project-level build.gradle:

classpath "io.gitlab.arturbosch.detekt:detekt-gradle-plugin:1.22.0"

App-level build.gradle:

apply plugin: "io.gitlab.arturbosch.detekt"

Then sync the project.

⚠️ Note: Detekt requires Gradle 6.1+

🧪 Run Detekt

To run Detekt and generate your first report:

./gradlew detekt

This analyzes your code using Detekt’s default configuration.

⚙️ Customize Configuration

Generate a configuration file to fine-tune the rules:

./gradlew detektGenerateConfig

It creates detekt.yml in your config/detekt/ directory.

Inside detekt.yml, enable or disable rules. For example:

comments:
  active: true
  excludes: "**/test/**,**/androidTest/**"

🧯 Add a Baseline (Optional for Legacy Projects)

To suppress existing issues in large codebases:

./gradlew detektBaseline

Then add it to your build.gradle:

detekt {
    baseline = file("config/detekt/baseline.xml")
}

🧰 Configuring Detekt in build.gradle

Here’s a sample setup for more control:

detekt {
    config = files("$rootDir/config/detekt/detekt.yml")
    buildUponDefaultConfig = false
    parallel = true
    allRules = false
    source = files("src/main/kotlin")
    ignoreFailures = false
}

✨ Creating a Custom Rule

Sometimes the default rules aren’t enough — say, banning deprecated APIs like Kotlin Android Extensions. Here’s how to add your own Detekt rule.

Step 1: Add Dependencies to Your customRules Module

// build.gradle of customRules module
compileOnly "io.gitlab.arturbosch.detekt:detekt-api:1.17.1"
testImplementation "io.gitlab.arturbosch.detekt:detekt-test:1.17.1"
testImplementation "org.assertj:assertj-core:3.19.0"
testImplementation 'junit:junit:4.13.2'

Step 2: Write a Custom Rule

class NoSyntheticImportRule : Rule() {
  override val issue = Issue(
    "NoSyntheticImport",
    Severity.Maintainability,
    "Don’t use Kotlin Synthetics, they are deprecated.",
    Debt.TWENTY_MINS
  )
  override fun visitImportDirective(importDirective: KtImportDirective) {
    val import = importDirective.importPath?.pathStr
    if (import?.contains("kotlinx.android.synthetic") == true) {
      report(
        CodeSmell(issue, Entity.from(importDirective),
        "Importing '$import' which is a Kotlin Synthetics import.")
      )
    }
  }
}

Step 3: Register RuleSetProvider

class CustomRuleSetProvider : RuleSetProvider {
  override val ruleSetId = "synthetic-import-rule"
  override fun instance(config: Config): RuleSet =
      RuleSet(ruleSetId, listOf(NoSyntheticImportRule()))
}

Then, in src/main/resources/META-INF/services/io.gitlab.arturbosch.detekt.api.RuleSetProvider, add:

com.yourpackage.CustomRuleSetProvider

🧪 Test Your Rule

class NoSyntheticImportTest {
  @Test
  fun noSyntheticImports() {
    val findings = NoSyntheticImportRule().lint("""
      import kotlinx.android.synthetic.main.activity_main.*
    """.trimIndent())
    assertThat(findings).hasSize(1)
    assertThat(findings[0].message).contains("Kotlin Synthetics")
  }
}

Run the test — ✅ Your rule is live!

📦 Use Your Custom Rule in Your Project

In app/build.gradle:

dependencies {
  detekt "io.gitlab.arturbosch.detekt:detekt-cli:1.17.1"
  detekt project(":customRules")
}

In detekt.yml:

synthetic-import-rule:
  active: true
  NoSyntheticImportRule:
    active: true

Run Detekt again:

./gradlew detekt

Boom 💥 — Your rule flags synthetic imports!

🚀 Wrapping Up

You’ve just: ✅ Integrated Detekt into Android Studio ✅ Customized your Detekt configuration ✅ Written, tested, and integrated a custom rule ✅ Enforced Kotlin coding best practices automatically

Static analysis is one of the easiest ways to improve code quality and catch issues before runtime — and with Detekt, it’s beautifully Kotlin-native.

📌 Sample project: GitHub — detekt_sample_app

💬 Got feedback or questions? Drop them in the comments!


메타데이터
post_id
a0a434d7d83c
slug
supercharge-your-kotlin-codebase-with-detekt-integration-custom-rules-a0a434d7d83c
url
https://medium.com/@shahricha723/supercharge-your-kotlin-codebase-with-detekt-integration-custom-rules-a0a434d7d83c
canonical_url
https://medium.com/@shahricha723/supercharge-your-kotlin-codebase-with-detekt-integration-custom-rules-a0a434d7d83c
author_url
https://medium.com/@shahricha723
status
ok
fetched_at
2026-06-18 07:02:39