What it is
ktlint is an anti-bikeshedding linter and formatter for Kotlin that enforces the official style guide with essentially no configuration.
Run as a Gradle task or a git hook. ktlintFormat rewrites files; ktlintCheck fails the build on violations.
Installation
plugins { id("org.jlleitschuh.gradle.ktlint") version "12.1.1" }Getting started
The smallest useful thing you can do with it, and what each part means.
kotlin
ktlint {
version.set("1.3.1")
android.set(true)
ignoreFailures.set(false)
reporters { reporter(ReporterType.CHECKSTYLE) }
filter { exclude("**/generated/**") }
}
// ./gradlew ktlintFormat fixes what it can
// ./gradlew ktlintCheck fails the build otherwise
// Install a pre-commit hook so nothing unformatted is committed:
// ./gradlew addKtlintCheckGitPreCommitHookAdvanced usage
Where the library earns its place over a simpler alternative.
# .editorconfig — ktlint reads its configuration from here
[*.{kt,kts}]
ktlint_code_style = intellij_idea
max_line_length = 120
indent_size = 4
ij_kotlin_allow_trailing_comma = true
# Disable a specific rule, project-wide.
ktlint_standard_no-wildcard-imports = disabled
# Suppress in one place, with a reason.
@Suppress("ktlint:standard:max-line-length") // generated URL, cannot wrap
private const val ENDPOINT = "https://…"Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- The formatter and the IDE disagree
- Both read .editorconfig. Set ktlint_code_style there and enable the IDE's EditorConfig support.
- Rule id not found when suppressing
- Rule ids are namespaced since 1.0 — use ktlint:standard:rule-name, not the bare name.
Best practices
- Run ktlintFormat in a pre-commit hook so review never discusses formatting.
- Exclude generated sources or the build will fail on code you do not control.
- Pair with detekt: ktlint handles formatting, detekt handles complexity and correctness.
- Resist adding rule exceptions; the value comes from there being no debate.
Background
Why it exists, and what it was reacting to.
ktlint's stated goal is to end style debates by having no meaningful options. It implements the official Kotlin coding conventions and formats to them.
