Introduction
ktlint enforces the official Kotlin coding conventions and the Android Kotlin style guide with no configuration needed. It combines linting and formatting in a single tool, eliminating style debates in code review by applying a consistent, opinionated standard.
What ktlint Does
- Lints Kotlin files against the official Kotlin coding conventions
- Auto-formats code with the
-Fflag to fix style violations in place - Runs as a standalone CLI, Gradle task, or Maven plugin
- Supports
.editorconfigfor customizing indentation and line length - Provides a reporter API for custom output formats
Architecture Overview
ktlint uses the Kotlin compiler embeddable library to parse source files into a PSI tree. Rules are visitors that inspect and optionally modify PSI nodes. The rule engine runs in two phases: first a lint pass to collect violations, then an optional format pass to apply fixes. Rules are loaded from the built-in standard rule set or from custom rule JAR files on the classpath.
Self-Hosting & Configuration
- Install via Homebrew, SDKMAN, snap, or download the JAR from GitHub releases
- Use
.editorconfigto setindent_size,max_line_length, and other formatting options - Integrate with Gradle via the
ktlint-gradleplugin or the official Gradle task - Add a pre-commit hook with
ktlint installGitPreCommitHook - Disable specific rules with
ktlint_disabled_rulesin.editorconfig
Key Features
- Zero-configuration default based on the official Kotlin coding conventions
- Built-in formatter that fixes violations rather than just reporting them
- EditorConfig support for project-specific overrides without a custom config file
- Git pre-commit and pre-push hook installation with a single command
- Custom rule set support via JAR files for organization-specific conventions
Comparison with Similar Tools
- Detekt — covers broader analysis including complexity and code smells; ktlint focuses on formatting and style
- IntelliJ formatter — IDE-specific; ktlint runs in CI without an IDE
- Spotless — a multi-language formatting tool that can delegate to ktlint as a backend
- Diktat — a stricter rule set built on top of ktlint's infrastructure
FAQ
Q: Does ktlint require any configuration to get started?
A: No. ktlint works out of the box with the official Kotlin coding conventions. Use .editorconfig only if you need to override defaults.
Q: Can I use ktlint with Android projects? A: Yes. ktlint supports the Android Kotlin style guide variant and integrates with Gradle-based Android projects.
Q: How do I suppress a rule for a specific block of code?
A: Use @Suppress("ktlint:standard:rule-name") annotation or // ktlint-disable comments.
Q: Does ktlint support Kotlin script files?
A: Yes. ktlint analyzes both .kt and .kts files including Gradle build scripts.