Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Kotlin Coding Conventions and Idioms

Kotlin Coding Conventions and Idioms

Code that runs is only the passing grade; team collaboration also requires consistent style and idiomatic writing.

This chapter covers Kotlin's officially recommended naming conventions, formatting rules, and the common idioms beginners most often get wrong.


Why a unified style is needed

Code is read far more often than it is written; a consistent style significantly lowers the cost of reading.

Consistent naming means callers don't have to guess what a function does, and consistent formatting keeps code reviews focused on logic rather than whitespace.

Kotlin has published official code style conventions, and IntelliJ IDEA's built-in formatter follows them by default.

The community also provides two tools, ktlint and detekt, which can integrate style checks into the build process and catch issues automatically before committing.

Tool Locate Typical usage
IDEA formatter Built into the editor; format with a shortcut Ctrl+Alt+L or Cmd+Option+L
ktlint Lightweight style checking and auto-fixing ./gradlew ktlintFormat
detekt Static code analysis covering complexity and code smells ./gradlew detekt

Naming conventions

Naming is the most frequent element in code; consistent naming rules are more effective than any comment.

Kotlin's naming conventions are basically the same as Java's, with a few Kotlin-specific touches such as constants and test methods.

Element Convention Example
Package name All lowercase, no underscores, multiple words joined directly com.runoob.demo
Classes and interfaces UpperCamelCase SiteInfo、DataRepository
Functions and methods lowerCamelCase getSiteName()、findById()
Constant All uppercase with underscores, used with const val or val const val MAX_COUNT = 100
Properties and local variables lowerCamelCase; avoid meaningless single letters siteName、pageSize
Type parameters A single uppercase letter, or UpperCamelCase with a T suffix T、TResult
Enum values All uppercase with underscores RED、DARK_BLUE
Files and directories Keep consistent with the top-level class name in the file SiteInfo.kt
Test methods On the JVM, backticks can wrap natural-language descriptions fun add returns sum()

Don't use underscores in package names; unlike some other languages, com.runoob_demo is incorrect.

Boolean properties should start with is, has, or can so their meaning is immediately clear.

Example

// File path: src/main/kotlin/com/runoob/Site.kt

package

com.runoob

// Class names in UpperCamelCase

data

class

Site

(

val name

:

String

, val url

:

String

)

{

   

// Boolean properties start with is, reading like a sentence

    val isSecure

:

Boolean

        get

(

)

=

url.

startsWith

(

"https://"

)

}

// Top-level constants in all uppercase

const

val MAX_SITE_COUNT

=

100

// Top-level functions in lowerCamelCase

fun describeSite

(

site

:

Site

)

:

String

=

"${site.name} -> ${site.url}"

fun main

(

)

{

    val site

=

Site

(

"Runoob"

,

"https://www.runoob.com"

)

    println

(

describeSite

(

site

)

)

    println

(

"Secure connection: ${site.isSecure}"

)

    println

(

"Maximum number of sites: $MAX_SITE_COUNT"

)

}

The output is as follows.



Runoob -> https://www.runoob.com

是否安全连接:true

最大站点数:100

Tip:Backtick naming only applies to the JVM target; Kotlin/JS and Kotlin/Native don't support identifiers with spaces or special characters, so cross-platform projects should use regular names.


Formatting and indentation

The goal of formatting isn't beauty but keeping diffs small and not disturbing reviewers.

The four most important rules in the official conventions are: indent with 4 spaces, line width 120, opening brace on the same line, and no space before the colon.

Rule Convention Description
Indentation 4 spaces Never use Tab, to avoid inconsistent widths across editors
Maximum line width 120 characters When exceeded, break after an operator or comma
Opening brace At the end of the declaration line Not on a line of its own
Colon in type declarations No space before the colon, one space after val name: String
Colon in inheritance One space before the colon, one space after class Dog : Animal()
Comma One space after fun add(a: Int, b: Int)
Trailing comma Recommended for multi-line parameter lists Supported since Kotlin 1.4, making it easier to add or remove parameters later
import Sort alphabetically; don't use wildcards Avoid naming conflicts and make dependencies clear
Blank lines Separate logical blocks with blank lines Don't have more than three consecutive blank lines

The trailing comma is a feature introduced in Kotlin 1.4; adding a comma after the last element of a multi-line parameter or element list is not an error.

Example

// File path: src/main/kotlin/com/runoob/Config.kt

package

com.runoob

// Use a trailing comma in multi-line parameter lists so adding or removing parameters later only affects one line of the diff

fun createSiteMap

(

    name

:

String

,

    url

:

String

,

    port

:

Int,

)

:

Map

<

String

, Any

{

   

return

mapOf

(

       

"name"

to name,

       

"url"

to url,

       

"port"

to port,

   

)

}

fun main

(

)

{

    println

(

createSiteMap

(

"Runoob"

,

"www.runoob.com"

,

443

)

)

}

The output is as follows.



{name=Runoob, url=www.runoob.com, port=443}

IDEA's format shortcut is Ctrl+Alt+L, or Cmd+Option+L on macOS; get into the habit of formatting once before committing.


Idioms

Kotlin provides many syntax features that reduce boilerplate; used well, they can cut your code by more than half.

The six idioms below are the most frequently used in everyday development.

Prefer val

Use var only when you truly need to reassign; otherwise always use val.

Immutable references eliminate hard-to-track bugs like "the value was changed elsewhere" and let the compiler optimize more.

Example

fun main

(

)

{

   

// Recommended: use val when the value won't change after being set

    val siteName

=

"Runoob"

    val url

=

"www.runoob.com"

   

// Use var only when accumulation is needed

    var visitCount

=

0

    visitCount

+=

1

    println

(

"$siteName -> $url, visits $visitCount"

)

}

The output is as follows.



Runoob -> www.runoob.com,访问次数 1

Note:val only guarantees the reference itself is immutable, not the object's contents. After val list = mutableListOf(1) you can still call list.add(2).

Use data classes instead of handwritten boilerplate

For classes that carry data, always use data class; the compiler automatically generates equals, hashCode, toString, copy, and destructuring methods.

Handwriting these methods is not only verbose but also easy to forget to update when adding new fields.

Example

// One line of declaration gives you five auto-generated methods

data

class

Site

(

val name

:

String

, val url

:

String

)

fun main

(

)

{

    val site

=

Site

(

"Runoob"

,

"www.runoob.com"

)

   

// toString generated automatically

    println

(

site

)

   

// copy duplicates the object and modifies specified fields

    val mobile

=

site.

copy

(

url

=

"m.runoob.com"

)

    println

(

mobile

)

   

// equals compares by content

    println

(

site

==

Site

(

"Runoob"

,

"www.runoob.com"

)

)

}

The output is as follows.



Site(name=Runoob, url=www.runoob.com)

Site(name=Runoob, url=m.runoob.com)

true

Use extension functions instead of utility classes

In Java you're used to writing utility classes like StringUtils and DateUtils; in Kotlin the more natural approach is extension functions.

Extension functions turn call sites into the form "object.method()", which is especially handy for chained calls.

Example

// Recommended: add an extension function to String instead of creating a utility class

fun

String

.

toDomain

(

)

:

String

=

    substringAfter

(

"://"

)

.

substringBefore

(

"/"

)

fun main

(

)

{

    val url

=

"https://www.runoob.com/kotlin"

    println

(

url.

toDomain

(

)

)

}

The output is as follows.



www.runoob.com

Extension functions are resolved statically; don't use them as a polymorphism mechanism; use inheritance or interfaces when you need polymorphism.

Use scope functions to simplify object operations

apply returns the object itself, good for centralized initialization; let returns the lambda result, good for transformations; also is good for side effects like logging.

Which one to choose depends on whether you want the object itself or the lambda's result.

Example

data

class

Site

(

var name

:

String

, var url

:

String

)

fun main

(

)

{

   

// apply returns the configured object, saving a temporary variable

    val site

=

Site

(

""

,

""

)

.

apply

{

        name

=

"Runoob"

        url

=

"www.runoob.com"

   

}

   

// also returns the object itself, often used for logging

    val upper

=

site.

also

{

println

(

"Configuration complete: $it"

)

}

        .

url

.

uppercase

(

)

    println

(

upper

)

}

The output is as follows.



配置完成:Site(name=Runoob, url=www.runoob.com)

WWW.RUNOOB.COM

Use when instead of long if-else chains

When there are more than two branches, a when expression is clearly more readable than an if-else chain.

Combined with sealed classes or enums, when can also do exhaustiveness checking; the compiler reports an error if a branch is missing.

Example

sealed

interface

Result

data

class

Success

(

val data

:

String

)

:

Result

data

class

Failure

(

val message

:

String

)

:

Result

// When used as an expression, all subtypes of the sealed type are covered, so no else branch is needed

fun describe

(

result

:

Result

)

:

String

=

when

(

result

)

{

    is Success

->

"Success: ${result.data}"

    is Failure

->

"Failure: ${result.message}"

}

fun main

(

)

{

    println

(

describe

(

Success

(

"RUNOOB"

)

)

)

    println

(

describe

(

Failure

(

"Network timeout"

)

)

)

}

The output is as follows.



成功:RUNOOB

失败:网络超时

Use null safety instead of non-null assertions

!! throws a null pointer exception immediately when the value is null, pushing the problem to runtime.

Prefer the safe call ?. and the Elvis operator ?: to handle null cases explicitly.

Example

fun main

(

)

{

    val name

:

String

?

=

null

   

// Safe call plus Elvis, giving a default value when null

    println

(

name

?

.

length

?:

0

)

    println

(

name

?

.

uppercase

(

)

?:

"File %s type is: %s%n"

)

    val site

:

String

?

=

"www.runoob.com"

   

// Only perform subsequent operations when non-null

    site

?

.

let

{

println

(

"Site length: ${it.length}"

)

}

}

The output is as follows.



0

未知

站点长度:14

Only use !! when you have logically guaranteed the value is non-null and null would indicate a serious bug, so the problem surfaces as early as possible.


Anti-pattern comparison table

The following patterns are common in the learning stage; comparing and fixing them can raise your code quality a notch.

Not recommended Recommended approach Reason
var count = 0 (never modified afterwards) val count = 0 Immutable references are safer
if (x != null) { x.foo() } x?.foo() Null-safe calls are more concise
x!!.foo() x?.foo() ?: return Avoid runtime null pointer exceptions
Handwriting equals, hashCode, toString data class Generated automatically by the compiler; no fields missed
Static methods in object StringUtils Extension functions or top-level functions More natural at call sites
for (i in 0 until list.size) for (item in list) Avoid index out of bounds
Deeply nested if-else when Expressions Clearer branch structure
Returning null to indicate failure sealed class or Result The failure reason can be carried along, with clear semantics
StringBuilder for string concatenation String template "$name" Better readability
Writing a getter method getSiteName() Property syntax siteName Kotlin automatically generates the accessor

These rules aren't absolute; for example, in performance-sensitive loops an explicit index is sometimes faster than an iterator.

But choose the recommended style by default, and deviate only with a clear reason.


Common questions

The following questions are asked most often when putting coding conventions into practice.

What if team conventions conflict with official ones

Go by the team's convention, but write it into a config file and let tools check it automatically rather than relying on verbal reminders.

ktlint's .editorconfig and detekt's detekt.yml both allow customizing rules.

Do extension functions pollute the global namespace

Extension functions must be imported to be used; they aren't automatically visible.

Put them in a dedicated package or file and control their scope with import.

Does a trailing comma affect compatibility

The trailing comma is a language feature supported since Kotlin 1.4; compilers older than 1.4 report an error.

New projects needn't worry; older projects can enable it after upgrading the compiler.

Can backtick naming be used outside tests

Syntactically yes, but it's only recommended for test methods; production code should still follow standard naming.