Skip to content
Tutorials Center
My learning

Topics

Lesson 121 of 134 ยท Testing and Tooling

Code Style, ktlint and detekt

Learn the official Kotlin coding conventions, how ktlint formats code, how detekt finds code smells, and how to wire both into Gradle and CI, with a mini linter you can run here.

Code is read far more often than it is written. When every file in a project follows the same rules for names, spacing and structure, you can skip the question "who wrote this and how?" and concentrate on what the code does. Style rules also remove pointless arguments in code review: nobody debates brace placement when a tool decides it.

Kotlin has an official set of coding conventions, and two popular tools enforce them. ktlint is a formatter and style checker: it deals with layout and naming and can fix most problems automatically. detekt is a static analyzer: it looks for code smells such as functions that are too long, too complex or too deeply nested. This lesson explains the conventions, shows both tools' configuration read-only (they need Gradle, which this site's runner does not have), and then builds a tiny linter you can run and extend yourself so you understand what such tools do.

The official conventions in five minutes

The Kotlin team publishes a style guide, and IntelliJ IDEA and Android Studio can apply it with one setting. The rules you will meet every day:

  • Names. Classes, interfaces, objects and type aliases use PascalCase (OrderService). Functions, properties and local variables use camelCase (totalPrice). Constants (const val, or a top-level or object val that holds a deeply immutable value) use SCREAMING_SNAKE_CASE (MAX_RETRIES). Package names are lowercase with no underscores (com.example.orders).
  • Indentation. Four spaces, never tabs. Lines are kept to about 100 or 120 characters, depending on the team.
  • Braces. The opening brace goes at the end of the line, the closing brace sits on its own line.
  • Trailing commas. When parameters, arguments or enum entries are on separate lines, end the last one with a comma. Adding an item then changes one line in the diff, not two.
  • Expression bodies. A function that is a single expression reads best as fun area() = width * height.
  • Immutability first. Prefer val over var, read-only collections over mutable ones, and data class for plain data.
  • Idioms over loops. Use map, filter, firstOrNull, when and string templates instead of manual index loops and string concatenation. See Idioms for a longer list.
  • Name arguments when the meaning of a literal is not obvious: connect(timeoutMs = 500), not connect(500).

Backing names are a special case: a property with a private mutable backing field is conventionally called _items and exposed as items. And a @Composable function in Jetpack Compose is allowed to start with an uppercase letter, which is why linters have an exception for it.

The next example shows two versions of the same small program. They print the same lines, but the second follows the conventions and is much easier to scan.

Kotlin The same program, before and after style

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Both totals are 51.0. The second version is shorter, has no mutable variable, gets toString, equals and copy for free from the data class, and uses a named constant instead of a bare 50.0. A reviewer reads it in seconds.

ktlint: the formatter

ktlint checks code against the Kotlin conventions (and, optionally, Android or other rule sets) and can rewrite files to fix what it finds. It has no configuration language of its own for most things: it reads the standard .editorconfig file that many editors already understand.

INI
# .editorconfig
root = true

[*.{kt,kts}]
indent_size = 4
max_line_length = 100
insert_final_newline = true
ij_kotlin_allow_trailing_comma = true
ij_kotlin_allow_trailing_comma_on_call_site = true

# switch off one rule for the whole project
ktlint_standard_no-wildcard-imports = disabled

You run ktlint in three common ways: from the command line, from a Gradle plugin, or as an IDE plugin. The Gradle route is the most popular because it puts the check next to your build. A typical read-only setup in build.gradle.kts looks like this, using the community plugin (check the plugin page for the current version):

Kotlin
plugins {
    kotlin("jvm") version "2.4.0"
    id("org.jlleitschuh.gradle.ktlint") version "<current version>"
}

ktlint {
    version.set("<current ktlint version>")
    android.set(false)
    outputToConsole.set(true)
}

The plugin adds two tasks: ./gradlew ktlintCheck reports violations and fails the build, and ./gradlew ktlintFormat fixes the ones that can be fixed automatically (indentation, spacing, import order, trailing commas, final newline). Some problems cannot be repaired by a machine, for example a class name that breaks the naming rule, because renaming needs a decision.

Typical ktlint output is one line per problem, with the file, line, column, the message and the rule id in parentheses:

TEXT
src/main/kotlin/Orders.kt:12:1: Wildcard import (standard:no-wildcard-imports)
src/main/kotlin/Orders.kt:27:50: Exceeded max line length (100) (standard:max-line-length)
src/main/kotlin/Orders.kt:31:5: Missing trailing comma before ")" (standard:trailing-comma-on-declaration-site)

That rule id (standard:no-wildcard-imports) is also what you use in .editorconfig to switch a rule off, or in code to suppress it for a single spot with @Suppress("ktlint:standard:no-wildcard-imports").

detekt: the analyzer

A formatter looks at how code looks. detekt looks at how code is built. Its rules are grouped into rule sets, and the most useful are:

Rule set Examples of what it catches
complexity LongMethod, LongParameterList, CyclomaticComplexMethod, NestedBlockDepth, TooManyFunctions
style MagicNumber, ReturnCount, UnusedPrivateMember, ForbiddenComment
potential-bugs UnsafeCallOnNullableType (!!), EqualsWithHashCodeExist, UnreachableCode
exceptions TooGenericExceptionCaught, SwallowedException, PrintStackTrace
performance SpreadOperator, ForEachOnRange
coroutines GlobalCoroutineUsage, RedundantSuspendModifier, SleepInsteadOfDelay

You configure detekt in a YAML file. Only list the rules you want to change; everything else keeps its default:

YAML
# config/detekt/detekt.yml
build:
  maxIssues: 0           # any finding fails the build

complexity:
  LongMethod:
    threshold: 40
  CyclomaticComplexMethod:
    threshold: 12
  LongParameterList:
    functionThreshold: 6
    constructorThreshold: 8
    ignoreDefaultParameters: true

style:
  MagicNumber:
    ignoreNumbers: ['-1', '0', '1', '2']
    ignoreEnums: true
  ForbiddenComment:
    values: ['FIXME', 'STOPSHIP']

potential-bugs:
  UnsafeCallOnNullableType:
    active: true

And the Gradle side (again read-only, because this site cannot run Gradle):

Kotlin
plugins {
    id("io.gitlab.arturbosch.detekt") version "<current version>"
}

detekt {
    buildUponDefaultConfig = true
    config.setFrom("$rootDir/config/detekt/detekt.yml")
    baseline = file("$rootDir/config/detekt/baseline.xml")
}

./gradlew detekt runs the analysis and prints findings with rule names. Many teams also turn on the type-resolution tasks (detektMain, detektTest), which can see the types of expressions and therefore catch more, such as a suspend function that never suspends.

Baselines and suppressions

You rarely adopt detekt on a fresh project. On an existing codebase the first run may report thousands of findings. A baseline file records them all (./gradlew detektBaseline), so detekt only complains about new problems and you can pay the old debt down gradually.

For a single justified exception, suppress the rule right where it happens and say why:

Kotlin
@Suppress("MagicNumber") // protocol constant from the spec
private const val HEADER_SIZE = 12

A suppression with no explanation is a smell of its own. Prefer fixing the code; suppress only when the rule is wrong for that spot.

Where the tools run

A check that only runs on your laptop is a suggestion. Put it in three places and it becomes a rule:

flowchart LR
    A["Editor: format on save"] --> B["Git pre-commit hook: ktlintFormat"]
    B --> C["Pull request"]
    C --> D["CI: ktlintCheck + detekt + tests"]
    D -->|"findings"| E["Fix and push again"]
    E --> C
    D -->|"clean"| F["Merge"]

Style problems are caught as early as possible: in the editor, before commit, and finally in CI, which no one can skip.

Order matters in CI: run the style check first because it is the cheapest and fastest feedback. A pull request that fails on a missing trailing comma should fail within a minute, not after the full test suite. Pair this lesson with testing in Kotlin, which covers the tests that run in the same pipeline, and with Gradle basics for how tasks hook into ./gradlew check.

Build a mini linter

The best way to see what ktlint and detekt really do is to write a small version. The program below holds a source file as a list of lines and applies a few rules to it. Each rule is a function from the file to a list of findings. Notice the design: rules are plain data (name plus a check), so adding one means adding one entry.

Kotlin A tiny style linter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output lists each finding in file:line: message (rule) form, exactly like ktlint's output, and ends with a count per rule. Try changing maxLength, renaming the class to OrderService, or removing the trailing spaces on line 3, and watch the findings disappear. Real tools do the same job with a proper syntax tree instead of regular expressions, which is why they do not trip over a class word inside a string, but the structure (rules, findings, a report) is identical.

Complexity: a number that points at trouble

Many detekt rules are measurements. Cyclomatic complexity counts the independent paths through a function: start at 1, add 1 for every if, when branch, loop, &&, ||, ?: and catch. A value above roughly 10 to 15 is a warning that the function is hard to test, because you need one test per path.

The next example measures a function's complexity with a crude counter, then shows a refactoring that removes the branching by moving the rules into data. The measured behavior stays the same.

Kotlin Counting branches, then refactoring them away

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The refactored function has fewer paths and adding a new country is a data change instead of another else if. Note that the refactoring is not completely behavior-preserving here: the original gave heavy US parcels a different rate. Dropping a rule while "simplifying" is exactly the risk that tests protect against, so refactor only with tests in place.

Documenting code with KDoc and Dokka

Style tools check how code looks; KDoc explains what it means. A KDoc comment starts with /**, sits directly before a declaration, and is written in Markdown (not HTML, unlike Javadoc). The first paragraph is the summary; block tags come after it.

Kotlin
/**
 * Splits [total] cents between [people] as evenly as possible.
 *
 * The first `total % people` people receive one extra cent, so nothing is lost.
 * See [Money] for the unit.
 *
 * @param total the amount to split, in cents; must not be negative
 * @param people how many shares to produce; must be positive
 * @return a list with [people] entries that add up to [total]
 * @throws IllegalArgumentException if [people] is zero or negative
 * @sample com.example.samples.splitExample
 */
fun splitCents(total: Int, people: Int): List<Int> {
    require(people > 0) { "people must be positive" }
    val base = total / people
    val extra = total % people
    return List(people) { if (it < extra) base + 1 else base }
}

The tags you will use most:

Tag Meaning
@param name describes a function parameter (for a type parameter, write @param T)
@property name describes a property declared in a primary constructor
@return describes the returned value
@throws Type an exception callers should expect (Kotlin does not check them, so this is how they learn)
@see a pointer to related code or a link
@sample includes the body of another function as a code example
@suppress hides the declaration from the generated docs

Square brackets turn a name into a link: [total] links to the parameter, [Money] or [java.util.List] to a class. Good KDoc says what the code promises, not what the code does line by line, and mentions the rules (ranges, units, nullability) that the types cannot express.

Dokka is the official documentation engine for Kotlin. It reads KDoc comments and produces a browsable site (HTML) or other formats. In a Gradle project you apply the plugin and run a task; this cannot run on this site, so the snippet is read-only:

Kotlin
// build.gradle.kts
plugins {
    kotlin("jvm") version "2.4.0"
    id("org.jetbrains.dokka") version "2.0.0"
}
Terminal
./gradlew dokkaGenerate      # writes the site to build/dokka/html

Plugin and task names change between Dokka versions, so check the current Dokka documentation before copying the snippet. Dokka works best when public API comes with KDoc: a linter such as detekt can require it for public declarations (its documentation rules), which keeps the generated site complete.

Practical advice

  • Adopt the tools early. Formatting a small project is a one-time, mostly automatic change. Formatting a huge one is a painful, noisy commit.
  • Agree on rules once, then stop discussing them. Put .editorconfig and detekt.yml in the repository and review changes to them like code.
  • Commit formatting changes separately from behavior changes, so reviewers and git blame can tell them apart.
  • Do not silence a rule just because it is annoying. First ask what it protects. A MagicNumber warning usually means a constant deserves a name; a TooGenericExceptionCaught warning usually means a catch (e: Exception) hides real bugs (see exceptions).
  • Use a formatter for layout and an analyzer for design. Do not try to make one tool do both jobs.
  • Run them locally the way CI runs them. ./gradlew check should be the one command that does everything.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which pair of names follows the official Kotlin conventions?

    Classes use PascalCase and functions use camelCase. The only common exception is a Compose function, which may start with an uppercase letter.
  2. 2. What is the main difference between ktlint and detekt?

    ktlint is a formatter and style checker that can auto-fix many findings. detekt is a static analyzer with rule sets for complexity, potential bugs, exceptions and more.
  3. 3. Your team adds detekt to a ten-year-old project and the first run reports 3,000 findings. What is the usual way to adopt it?

    A baseline file records existing findings. New code is held to the rules while the old debt is paid down gradually.
  4. 4. Why should the style check run before the test suite in CI?

    Order is about speed of feedback. A missing trailing comma should not cost the full test run.
  5. 5. What does a cyclomatic complexity of 15 for one function tell you?

    Complexity counts decision points. A high value means many paths and therefore many tests, which is a smell.

Summary

  • The official conventions cover names (PascalCase types, camelCase functions, SCREAMING_SNAKE constants), four-space indentation, trailing commas, expression bodies and val-first, idiomatic code.
  • ktlint reads .editorconfig, reports layout and naming problems with rule ids, and ktlintFormat fixes most of them automatically.
  • detekt reads a YAML config, groups rules into sets (complexity, style, potential-bugs, exceptions, coroutines) and fails the build above maxIssues.
  • Use a baseline to adopt detekt on an old codebase and @Suppress with a reason for rare, justified exceptions.
  • Enforce the tools in the editor, in a pre-commit hook and in CI, with the cheap style check first.
  • Complexity numbers point at functions worth simplifying, but refactor only when tests protect the behavior.

Next, put the tools to work in a real codebase with Project: Calculator.