Skip to content

What it is

detekt is a static analysis tool for Kotlin, detecting code smells, complexity problems, potential bugs and style violations, with baseline support for existing codebases.

Configure rule sets in YAML, run as a Gradle task, and fail the build on violations. A baseline file suppresses pre-existing issues.

Installation

plugins { id("io.gitlab.arturbosch.detekt") version "1.23.7" }

Getting started

The smallest useful thing you can do with it, and what each part means.

Configuration and baseline
detekt {
    buildUponDefaultConfig = true
    config.setFrom("$projectDir/config/detekt.yml")
    baseline = file("$projectDir/config/baseline.xml")
    autoCorrect = true
}

tasks.withType<Detekt>().configureEach {
    reports { html.required.set(true); sarif.required.set(true) }
}

// Generate the baseline once on an existing codebase:
//   ./gradlew detektBaseline
// Existing violations are frozen; new ones fail the build.
Without a baseline, enabling detekt on a mature codebase produces thousands of failures and gets switched off. With one, the ratchet only tightens.

Advanced usage

Where the library earns its place over a simpler alternative.

Rules worth enabling, and suppression
complexity:
  LongMethod:
    threshold: 40
  CyclomaticComplexMethod:
    threshold: 15

potential-bugs:
  UnsafeCallOnNullableType:
    active: true          # flags every !!
  IgnoredReturnValue:
    active: true

coroutines:
  GlobalCoroutineUsage:
    active: true          # catches GlobalScope
  SuspendFunWithFlowReturnType:
    active: true
GlobalCoroutineUsage and UnsafeCallOnNullableType are the two highest-value rules for Kotlin specifically — they catch the leak and the crash that Kotlin's design otherwise makes easy to introduce.

Errors and fixes

The failures you are most likely to hit, and what actually resolves them.

Thousands of violations on first run
Run detektBaseline to freeze the existing ones, then fix them incrementally.
Type-resolution rules do not fire
Those rules need the detektMain task with classpath configured, not the plain detekt task.

Best practices

  • Generate a baseline when adopting on an existing project, then never regenerate it wholesale.
  • Enable the coroutines rule set; GlobalScope misuse is a real production issue.
  • Fail the build on violations in CI, or the tool becomes advisory and is ignored.
  • Pair with ktlint for formatting — detekt covers correctness and complexity, not layout.

Background

Why it exists, and what it was reacting to.

detekt gives Kotlin the equivalent of what ESLint provides for JavaScript. Its baseline feature is what makes adoption realistic on a large existing project — freeze current violations and block new ones.