Coding conventions
suggest changeKotlin 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:
- naming: how to name packages, classes, functions, properties and constants
- formatting: indentation, spacing, wrapping of long lines, trailing commas
- idioms: which language feature to use when there are several ways to write the same thing
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:
- Constants: SCREAMING_SNAKE_CASE is only for values that are truly constant. A
valholding aMutableListor an object with mutable state is named in camelCase, even if it's at top level or in a companion object. - Acronyms: a two-letter acronym stays uppercase (
IOStream), a longer one is capitalized like a word (HttpClient,XmlParser, notHTTPClient). - Backing properties: when a class exposes a read-only view of private mutable state, the private property gets an underscore prefix (
_items) and the public one the plain name (items). This is common in Android view models with_stateandstate. - Factory functions may be named like the class they create (
fun Cart(vararg names: String)), so they read like a constructor call. The standard library does this withList(5) { it }andMutableStateFlow(0).
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
- A file that contains a single class is named after the class:
Cart.kt. - A file with several declarations, or only top-level functions, gets a name that describes its contents in UpperCamelCase:
StringExtensions.kt,Routing.kt. Avoid generic names likeUtil.kt. - Putting several small, closely related classes in one file is fine (a sealed class and its subclasses, for example), as long as the file stays reasonably small.
- In pure Kotlin projects, the directory structure follows the package structure with the common root package omitted: if every package starts with
com.example.shop, the file forcom.example.shop.cart.Cartgoes incart/Cart.kt.
Class layout
Declarations inside a class follow this order:
- property declarations and
initblocks - secondary constructors
- methods
- nested and inner classes
- 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:
- indent with 4 spaces, never tabs
- put the opening brace at the end of the line, the closing brace on its own line
- no semicolons at the end of lines
- spaces around binary operators (
a + b,x..yis the exception: no spaces) - no space before
:when it separates a name from its type (name: String), but a space on both sides when it separates a class from its supertype (class Widget : Base()) - spaces after
if,when,forandwhile, but not between a function name and its(
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
- put spaces inside the braces and around the arrow:
list.filter { it > 10 } - if the last parameter is a lambda, pass it outside the parentheses:
items.map { it.name }, notitems.map({ it.name }) - if the lambda is the only argument, drop the parentheses entirely
- use
itin short, single-level lambdas; name the parameter when the lambda is long or nested
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:
- Expression bodies: a function whose body is a single expression is written with
=. Useif,whenandtryas expressions instead of assigning avarin each branch (see If-statement as an expression). whenoverifchains: with three or more branches,whenis easier to read. Useiffor binary conditions.- Default arguments over overloads: one function with default values replaces several overloads. See Named and optional parameters.
- Named arguments for literals:
connect("localhost", port = 8080, secure = false)is readable;connect("localhost", 8080, false)makes the reader look up whatfalsemeans. Always nameBooleanarguments unless the function name makes them obvious. - Property or function: use a property when the value is cheap to compute, has no side effects, doesn't throw and returns the same result while the object doesn't change. Otherwise use a function.
- Extension functions: instead of a
StringUtilsclass full of static methods, write extension functions. Keep their visibility as narrow as possible, for exampleprivatein the file that uses them. - Index operators:
map[key]instead ofmap.get(key),list[0]instead oflist.get(0). - No
!!: handlenullwith?.,?:,letor an early return. When a value must not be null, userequireNotNullorcheckNotNullwith a message, so the exception says what went wrong. See Elvis Operator.
A few more rules in the same spirit:
- prefer
valovervar, and read-onlyList,SetandMapover mutable ones in function signatures (see Immutability) - use string templates (
"Hello, $name") instead of concatenation with+ - use
listOf(),mapOf(),setOf()instead of Java constructors likeArrayList()when you don't need a specific implementation - use ranges and
until/..<for loops:for (i in 0..<n) - leave out types that the compiler can infer and the reader can see, such as
val count = 0, but write the return type of public functions that have a block body - omit
Unitas a return type, and don't write areturnat the end of aUnitfunction - use a
typealiasfor long function types or generic types that appear many times
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
- Use the official Kotlin coding conventions: set
kotlin.code.style=officialand let the IDE format the code. - Classes are UpperCamelCase, functions and properties lowerCamelCase, true constants SCREAMING_SNAKE_CASE, backing properties start with
_. - Order class members as properties and
init, secondary constructors, methods, nested classes, companion object. Group methods by meaning. - Indent with 4 spaces, wrap long parameter lists one per line, wrap chained calls before the
., use trailing commas. - Prefer expression bodies,
when, default and named arguments, extension functions,valand read-only collections. Avoid!!. - Pick scope functions by what they return, and don't nest them.
- In libraries, turn on explicit API mode.
- Enforce all of this with ktlint (and optionally detekt) in the build, configured through
.editorconfig.