Coding conventions

suggest change

Kotlin has an official style guide, the Kotlin coding conventions, maintained by JetBrains. IntelliJ IDEA and Android Studio implement it in their formatter, and linters like ktlint enforce it. Following it means your code looks like the standard library, like the code of every major Kotlin project, and like the examples in the documentation.

The conventions cover three things:

This article goes through the rules that matter most in practice, then shows how to enforce them automatically so code review doesn't have to.

Turning on the official style

New projects created by IntelliJ IDEA already use the official style. For older projects, add this to gradle.properties so the IDE formatter uses the current conventions instead of the old defaults:

kotlin.code.style=official

In the IDE, Code | Reformat Code (Ctrl+Alt+L on Windows and Linux, Cmd+Opt+L on macOS) then formats a file according to the guide.

Naming

The rules are short:

What Style Example
packages lowercase, no underscores com.example.shop
classes, interfaces, objects, type aliases UpperCamelCase OrderRepository
functions, properties, local variables, parameters lowerCamelCase totalPrice, findUser()
const val and top-level or object val holding deeply immutable data SCREAMING_SNAKE_CASE MAX_CART_ITEMS
enum entries SCREAMING_SNAKE_CASE or UpperCamelCase PAID or Paid
backing property underscore prefix _items

Here they are together in a program:

package com.example.shop

import java.util.concurrent.TimeUnit

const val MAX_CART_ITEMS = 50                       // compile-time constant
val DEFAULT_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(30) // deeply immutable top-level val

interface Shape { fun area(): Double }

class HttpClient                                 // acronym longer than 2 letters: Http
class IOStream                                   // 2-letter acronym: both uppercase

class Cart {
    private val _items = mutableListOf<String>() // backing property
    val items: List<String> get() = _items

    fun addItem(name: String) {
        check(_items.size < MAX_CART_ITEMS) { "cart is full" }
        _items += name
    }

    companion object {
        private val log = mutableListOf<String>() // not a constant: camelCase
    }
}

enum class OrderStatus { NEW, PAID, SHIPPED }    // UPPER_CASE or UpperCamelCase entries

// Factory function named like the type it creates
fun Cart(vararg names: String): Cart = Cart().apply { names.forEach(::addItem) }

fun main() {
    val cart = Cart("apple", "pear")
    println(cart.items)
    println(DEFAULT_TIMEOUT_MS)
    println(OrderStatus.entries)
}
[apple, pear]
30000
[NEW, PAID, SHIPPED]

A few details worth calling out:

Names should say what something is or does. Classes are nouns (OrderRepository), functions are verbs (calculateTotal()). Avoid meaningless suffixes such as Manager or Wrapper when a more precise name exists.

A function that returns a modified copy is named with a participle, while a function that modifies the object in place uses the verb: sorted() returns a new list, sort() sorts a MutableList in place. Follow the same pattern in your own APIs.

In tests, and only in tests, you can use backticks to write function names as sentences:

class CartTest {
    @Test
    fun `adding an item beyond the limit throws`() {
        // ...
    }
}

Source files

Class layout

Declarations inside a class follow this order:

  1. property declarations and init blocks
  2. secondary constructors
  3. methods
  4. nested and inner classes
  5. companion object
class Order(val id: Long, items: List<Line>) {
    // 1. Properties and init blocks
    val lines: List<Line> = items.toList()
    val total: Long

    init {
        require(lines.isNotEmpty()) { "order $id has no lines" }
        total = lines.sumOf { it.priceCents * it.quantity }
    }

    // 2. Secondary constructors
    constructor(id: Long, vararg items: Line) : this(id, items.toList())

    // 3. Methods, grouped by what they do (not alphabetically, not by visibility)
    fun describe(): String = "Order #$id: ${lines.size} lines, ${formatCents(total)}"

    private fun formatCents(cents: Long) = "$%d.%02d".format(cents / 100, cents % 100)

    // 4. Nested classes
    data class Line(val sku: String, val priceCents: Long, val quantity: Int = 1)

    // 5. Companion object last
    companion object {
        fun sample() = Order(1, Line("BOOK-1", 1999), Line("PEN-7", 250, quantity = 4))
    }
}

fun main() {
    println(Order.sample().describe())
}
Order #1: 2 lines, $29.99

Don't sort methods alphabetically or by visibility, and don't move extension functions to the end of the class. Put related things together so someone reading the class from top to bottom can follow the logic. When a class implements an interface, keep the implementing members in the same order as in the interface.

When a declaration has several modifiers, they go in this order:

public / protected / private / internal
expect / actual
final / open / abstract / sealed / const
external
override
lateinit
tailrec
vararg
suspend
inner
enum / annotation / fun   // "fun" as in "fun interface"
companion
inline / value
infix
operator
data

So it's private const val, protected abstract fun, final override fun, override suspend fun and private inline fun. Annotations go before all modifiers: @JvmStatic private fun. Leave out modifiers that are the default, such as public or final on a non-overriding function (except in explicit API mode, described below).

Formatting

The basics:

Wrapping long declarations and calls

When a class header, a function signature or a call doesn't fit on one line, put each parameter on its own line, indented by 4 spaces, with the closing parenthesis on its own line. Chained calls are wrapped before the ., with each call on its own line:

data class Employee(
    val name: String,
    val department: String,
    val salary: Int,
    val active: Boolean = true, // trailing comma
)

fun report(
    employees: List<Employee>,
    minSalary: Int = 0,
    includeInactive: Boolean = false,
): String {
    val rows = employees
        .filter { includeInactive || it.active }
        .filter { it.salary >= minSalary }
        .sortedByDescending { it.salary }
        .map { "${it.name.padEnd(6)} ${it.department.padEnd(5)} ${it.salary}" }
    return rows.joinToString(separator = "\n")
}

fun main() {
    val staff = listOf(
        Employee("Ann", "eng", 120),
        Employee("Bob", "ops", 90),
        Employee("Cid", "eng", 100, active = false),
    )
    println(report(staff, minSalary = 95))
    println("--")
    println(report(staff, includeInactive = true))
}
Ann    eng   120
--
Ann    eng   120
Cid    eng   100
Bob    ops   90

Trailing commas

Notice the comma after the last parameter of Employee and report and after the last element of listOf(...). The conventions encourage trailing commas whenever the elements are on separate lines. Adding a new parameter then changes one line in the diff instead of two, and elements can be reordered without fixing commas. Trailing commas are allowed in parameter and argument lists, collection literals, when branches, destructuring declarations and type parameter lists.

Lambdas

Idiomatic code

The formatting rules are easy for a tool to check. The idioms are about choosing the right construct, which is where most review comments come from.

Prefer expressions, defaults and extensions

import java.time.LocalDate

// Expression body: the function is a single expression
fun isWeekend(date: LocalDate): Boolean = date.dayOfWeek.value >= 6

// when instead of an if-else-if chain
fun httpStatusText(code: Int): String = when (code) {
    200 -> "OK"
    301, 302 -> "Redirect"
    in 400..499 -> "Client error"
    in 500..599 -> "Server error"
    else -> "Unknown"
}

// Default parameter values instead of overloads
fun connect(host: String, port: Int = 443, secure: Boolean = true): String =
    "${if (secure) "https" else "http"}://$host:$port"

class Rectangle(val width: Int, val height: Int) {
    // cheap, no side effects, same result each time: a property
    val area: Int get() = width * height

    // does work or may change: a function
    fun scaled(factor: Int) = Rectangle(width * factor, height * factor)
}

// Extension function instead of a FooUtils class
fun String.toSlug(): String =
    lowercase().replace(Regex("[^a-z0-9]+"), "-").trim('-')

fun findUser(id: Int): String? = mapOf(1 to "ann")[id]

fun main() {
    println(isWeekend(LocalDate.of(2026, 10, 17)))
    println(listOf(200, 302, 404, 503, 42).map(::httpStatusText))
    println(connect("example.com"))
    println(connect("localhost", port = 8080, secure = false))

    val r = Rectangle(3, 4)
    println("${r.area} ${r.scaled(2).area}")
    println("Coding Conventions in Kotlin!".toSlug())

    // Handle null explicitly instead of using !!
    val name = findUser(2) ?: "guest"
    val required = requireNotNull(findUser(1)) { "user 1 must exist" }
    println("$name $required")
}
true
[OK, Redirect, Client error, Server error, Unknown]
https://example.com:443
http://localhost:8080
12 48
coding-conventions-in-kotlin
guest ann

The guidelines behind this code:

A few more rules in the same spirit:

Scope functions

let, run, with, apply and also overlap a lot, which makes it easy to pick one at random. The convention is to choose by what the block returns and how it refers to the object:

Function Object inside the block Returns Typical use
apply this the object configuring a new object
also it the object side effects such as logging or validation
let it lambda result transforming a nullable value with ?.let
run this lambda result computing a value from the object's members
with this lambda result calling several functions on one object
data class Config(var host: String = "", var port: Int = 0, var debug: Boolean = false)

fun loadPort(env: Map<String, String>): Int =
    env["PORT"]?.toIntOrNull() ?: 8080

fun main() {
    // apply: configure an object, returns the object
    val config = Config().apply {
        host = "localhost"
        port = loadPort(mapOf("PORT" to "9000"))
    }

    // also: side effect (logging), returns the object unchanged
    val copy = config.copy(debug = true).also { println("created $it") }

    // let: transform a nullable value, returns the lambda result
    val home = System.getenv("NO_SUCH_VARIABLE")?.let { "value: $it" } ?: "not set"

    // run: compute a value using the receiver
    val url = config.run { "http://$host:$port" }

    // Explicit names instead of nested `it`
    val pairs = listOf("a", "b").flatMap { letter ->
        listOf(1, 2).map { number -> "$letter$number" }
    }

    println(url)
    println(home)
    println(copy.debug)
    println(pairs)
}
created Config(host=localhost, port=9000, debug=true)
http://localhost:9000
not set
true
[a1, a2, b1, b2]

Don't nest scope functions, and don't chain several of them. Once a chain of let, also and run gets longer than a couple of lines, local variables with good names are easier to read. More examples are in Use let or also to simplify working with nullable objects and Use apply to initialize objects or to achieve method chaining.

Libraries: explicit API mode

Code that other projects depend on has extra rules: every public declaration should have an explicit visibility modifier and an explicit return type, so you don't make something public by accident and an implementation change can't silently change the type in your API. Kotlin can enforce this with explicit API mode. In Gradle:

// build.gradle.kts
kotlin {
    explicitApi()
}

On the command line it's -Xexplicit-api=strict. Given this file:

package com.example.lib

class Money(val cents: Long) {
    fun format() = "$%d.%02d".format(cents / 100, cents % 100)
}

internal fun helper() = 42

the compiler reports:

api.kt:3:1: error: visibility must be specified in explicit API mode.
class Money(val cents: Long) {
^^^^^^^^^^^
api.kt:3:13: error: visibility must be specified in explicit API mode.
class Money(val cents: Long) {
            ^^^^^^^^^
api.kt:4:5: error: visibility must be specified in explicit API mode.
    fun format() = "$%d.%02d".format(cents / 100, cents % 100)
    ^^^^^^^^^^
api.kt:4:9: error: return type must be specified in explicit API mode.
    fun format() = "$%d.%02d".format(cents / 100, cents % 100)
        ^^^^^^

The fix is to state what's public and what it returns. Declarations that are internal or private are not affected:

public class Money(public val cents: Long) {
    public fun format(): String = "$%d.%02d".format(cents / 100, cents % 100)
}

internal fun helper() = 42

Use explicitApiWarning() instead of explicitApi() to get warnings while you migrate an existing library. For applications, explicit API mode is unnecessary noise; leave it off.

Enforcing the conventions with ktlint

Style rules that depend on reviewers remembering them don't last. ktlint checks Kotlin code against the official conventions and fixes most violations automatically. It's a single executable JAR, needs no configuration, and is also available as a Gradle plugin (org.jlleitschuh.gradle.ktlint) and through Spotless.

Take this file:

import java.util.*

class Greeter(val name:String) {
  fun Greet():String{
      return "Hi, "+name;
  }
}

Running ktlint "src/**/*.kt" (ktlint 1.8.0, output shortened) gives:

src/Greeter.kt:1:1: Wildcard import (standard:no-wildcard-imports)
src/Greeter.kt:3:15: Newline expected after opening parenthesis (standard:class-signature)
src/Greeter.kt:3:24: Missing spacing after ":" (standard:colon-spacing)
src/Greeter.kt:3:30: Newline expected before closing parenthesis (standard:class-signature)
src/Greeter.kt:4:1: Unexpected indentation (2) (should be 4) (standard:indent)
src/Greeter.kt:4:7: Function name should start with a lowercase letter (except factory methods) and use camel case (standard:function-naming)
src/Greeter.kt:4:15: Missing spacing after ":" (standard:colon-spacing)
src/Greeter.kt:4:21: Missing spacing before "{" (standard:curly-spacing)
src/Greeter.kt:5:1: Unexpected indentation (6) (should be 8) (standard:indent)
src/Greeter.kt:5:20: Missing spacing around "+" (standard:op-spacing)
src/Greeter.kt:5:25: Unnecessary semicolon (standard:no-semi)
src/Greeter.kt:6:1: Unexpected indentation (2) (should be 4) (standard:indent)

ktlint -F "src/**/*.kt" fixes everything it can and reports the rest, here the wildcard import and the function name, which need a human decision:

import java.util.*

class Greeter(
    val name: String,
) {
    fun Greet(): String = "Hi, " + name
}

ktlint even converted the block body to an expression body. The constructor parameter was moved to its own line with a trailing comma because ktlint's default code style, ktlint_official, is slightly stricter than the IntelliJ formatter. To match the IDE formatter exactly, or to adjust individual rules, add an .editorconfig file at the project root:

root = true

[*.{kt,kts}]
indent_size = 4
max_line_length = 120
ktlint_code_style = intellij_idea
ktlint_standard_no-wildcard-imports = disabled

With intellij_idea style the class header stays class Greeter(val name: String) {. IntelliJ IDEA reads the same .editorconfig, so the IDE and the linter agree.

Run ktlint in CI (see Testing in CI) so formatting problems fail the build instead of showing up in review. For checks that go beyond formatting, such as overly complex functions, swallowed exceptions or magic numbers, add detekt, which includes ktlint's formatting rules as an optional rule set.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents