Setting Up Detekt for Kotlin Code Style Checking
Detekt is a static analyzer for Kotlin code. It finds code smells, checks function complexity, detects potentially unsafe code (unsafe !!, magic numbers, empty catch blocks). For Android projects, it works alongside Android Lint — they complement each other: Lint knows Android specifics (incorrect Context usage, memory leaks), Detekt — Kotlin idioms.
Connecting to Gradle
// build.gradle.kts (project level)
plugins {
id("io.gitlab.arturbosch.detekt") version "1.23.7"
}
detekt {
config.setFrom(files("$rootDir/detekt.yml"))
buildUponDefaultConfig = true
allRules = false
baseline = file("$rootDir/detekt-baseline.xml")
}
dependencies {
detektPlugins("io.gitlab.arturbosch.detekt:detekt-formatting:1.23.7")
detektPlugins("com.twitter.compose.rules:detekt:0.0.26") // Compose-specific rules
}
detektPlugins("io.gitlab.arturbosch.detekt:detekt-formatting") adds formatting via ktlint under the hood.
detekt.yml Configuration
build:
maxIssues: 0
excludeCorrectable: false
complexity:
LongMethod:
threshold: 50
CyclomaticComplexMethod:
threshold: 15
LongParameterList:
threshold: 6
ignoreDefaultParameters: true
TooManyFunctions:
thresholdInFiles: 20
thresholdInClasses: 15
style:
MagicNumber:
ignoreNumbers:
- '-1'
- '0'
- '1'
- '2'
ignoreEnums: true
ignoreConstantDeclaration: true
UnusedPrivateMember:
active: true
potential-bugs:
UnsafeCallOnNullableType:
active: true
UnreachableCode:
active: true
exceptions:
SwallowedException:
active: true
TooGenericExceptionCaught:
active: true
exceptionNames:
- Exception
- Throwable
Baseline
On existing projects, Detekt finds hundreds of violations. Running with maxIssues: 0 from scratch is unrealistic. Baseline fixes current state:
./gradlew detektBaseline
Creates detekt-baseline.xml with all existing violations. Detekt will complain only about new violations in new code. Baseline is committed to repository, gradually cleaned up during refactoring.
Running in CI
- name: Run Detekt
run: ./gradlew detekt
- name: Upload Detekt Report
uses: github/codeql-action/upload-sarif@v3
if: always()
with:
sarif_file: build/reports/detekt/detekt.sarif
SARIF format displays violations directly in GitHub Code Review as annotations. if: always() — upload report even if detekt fails, so we see violations in PR.
Compose-specific Rules
For Jetpack Compose projects add twitter-compose-rules:
detektPlugins("com.twitter.compose.rules:detekt:0.0.26")
Rules check: @Composable functions without @Preview, unstable parameters in @Composable, remember usage without keys where keys are needed. Real issues Android Lint doesn't cover.
Timeline: 1 day. Cost is calculated individually.







