Introduction
Detekt performs static code analysis on Kotlin projects to find code smells, complexity issues, and style violations. It integrates as a Gradle plugin and provides a CLI for standalone use. Its rule set is designed specifically for Kotlin idioms and patterns.
What Detekt Does
- Analyzes Kotlin source code for complexity, style, naming, and potential bugs
- Provides a Gradle plugin for seamless build integration
- Supports custom rule sets written in Kotlin
- Generates reports in HTML, XML, SARIF, and Markdown formats
- Offers auto-correction for a subset of formatting rules via the detekt-formatting wrapper
Architecture Overview
Detekt uses the Kotlin compiler embeddable library to parse Kotlin source files into a PSI (Program Structure Interface) tree. Rules are visitors that traverse the PSI tree and report findings. The configuration layer reads a YAML file (detekt.yml) that controls which rule sets are active and their threshold parameters. Type resolution is optional and enables deeper analysis when the Kotlin compiler classpath is provided.
Self-Hosting & Configuration
- Apply the Gradle plugin or download the CLI JAR from GitHub releases
- Generate a default config with
detekt --generate-configto createdetekt.yml - Set complexity thresholds like
maxLineLength,maxFunctionLength, andmaxCyclomaticComplexity - Enable type resolution by configuring
classpathandjvmTargetin the Gradle task - Add the
detekt-formattingplugin for ktlint-compatible formatting rules
Key Features
- Kotlin-specific rules that understand coroutines, sealed classes, and data classes
- Complexity metrics including McCabe complexity, lines of code, and nesting depth
- Baseline file support for incremental adoption on existing projects
- SARIF output for GitHub code scanning and IntelliJ IDEA integration
- Parallel analysis for faster execution on multi-module projects
Comparison with Similar Tools
- ktlint — focuses on formatting and style enforcement; Detekt covers broader analysis including complexity and code smells
- SonarQube — a full platform with dashboards and history; Detekt is a lightweight CLI and Gradle plugin
- IntelliJ inspections — built into the IDE; Detekt runs in CI without an IDE dependency
- Diktat — a stricter Kotlin coding convention enforcer; Detekt offers more configurable and flexible rules
FAQ
Q: Can Detekt analyze Kotlin Multiplatform projects? A: Yes. Configure Detekt for each source set in your Gradle build, and it will analyze common, JVM, JS, and Native source sets.
Q: How do I suppress a finding for a specific function?
A: Add @Suppress("DetektRuleName") annotation to the function, class, or file.
Q: Does Detekt support Kotlin script (.kts) files?
A: Yes. Detekt can analyze .kt and .kts files including Gradle build scripts.
Q: How do I create a custom rule?
A: Implement a class extending Rule, override the visitNamedFunction or other PSI visitor methods, and package it as a rule set provider in a separate module.