<commit_before>---
type: doc
layout: reference
category: Basics
title: Coding Conventions
---

# Coding Conventions

This page contains the current coding style for the Kotlin language.

* [Source code organization](#source-code-organization)
* [Naming rules](#naming-rules)
* [Formatting](#formatting)
* [Documentation comments](#documentation-comments)
* [Avoiding redundant constructs](#avoiding-redundant-constructs)
* [Idiomatic use of language features](#idiomatic-use-of-language-features)
* [Coding conventions for libraries](#coding-conventions-for-libraries)

### Applying the style guide

To configure the IntelliJ formatter according to this style guide, please install Kotlin plugin version
1.2.20 or newer, go to __Settings | Editor | Code Style | Kotlin__, click __Set from...__ link in the upper
right corner, and select __Kotlin style guide__ from the menu.

To verify that your code is formatted according to the style guide, go to __Settings | Editor | Inspections__ and enable
the __Kotlin | Style issues | File is not formatted according to project settings__ inspection. Additional
inspections that verify other issues described in the style guide (such as naming conventions) are enabled by default.

## Source code organization

### Directory structure

In pure Kotlin projects, the recommended directory structure follows the package structure with
the common root package omitted. For example, if all the code in the project is in the `org.example.kotlin` package and its
subpackages, files with the `org.example.kotlin` package should be placed directly under the source root, and
files in `org.example.kotlin.network.socket` should be in the `network/socket` subdirectory of the source root.

> **On the JVM**: In projects where Kotlin is used together with Java, Kotlin source files should reside in the same source root as the Java source files,
and follow the same directory structure: each file should be stored in the directory corresponding to each package
statement.

### Source file names

If a Kotlin file contains a single class (potentially with related top-level declarations), its name should be the same
as the name of the class, with the .kt extension appended. If a file contains multiple classes, or only top-level declarations,
choose a name describing what the file contains, and name the file accordingly.
Use the [camel case](https://en.wikipedia.org/wiki/Camel_case) with an uppercase first letter (for example, `ProcessDeclarations.kt`).

The name of the file should describe what the code in the file does. Therefore, you should avoid using meaningless
words such as "Util" in file names.

### Source file organization

Placing multiple declarations (classes, top-level functions or properties) in the same Kotlin source file is encouraged
as long as these declarations are closely related to each other semantically and the file size remains reasonable
(not exceeding a few hundred lines).

In particular, when defining extension functions for a class which are relevant for all clients of this class,
put them in the same file where the class itself is defined. When defining extension functions that make sense 
only for a specific client, put them next to the code of that client. Do not create files just to hold 
"all extensions of Foo".

### Class layout

Generally, the contents of a class is sorted in the following order:

- Property declarations and initializer blocks
- Secondary constructors
- Method declarations
- Companion object

Do not sort the method declarations alphabetically or by visibility, and do not separate regular methods
from extension methods. Instead, put related stuff together, so that someone reading the class from top to bottom can 
follow the logic of what's happening. Choose an order (either higher-level stuff first, or vice versa) and stick to it.

Put nested classes next to the code that uses those classes. If the classes are intended to be used externally and aren't
referenced inside the class, put them in the end, after the companion object.

### Interface implementation layout

When implementing an interface, keep the implementing members in the same order as members of the interface (if necessary,
interspersed with additional private methods used for the implementation)

### Overload layout

Always put overloads next to each other in a class.

## Naming rules

Package and class naming rules in Kotlin are quite simple:

* Names of packages are always lower case and do not use underscores (`org.example.project`). Using multi-word
names is generally discouraged, but if you do need to use multiple words, you can either simply concatenate them together
or use the camel case (`org.example.myProject`).

* Names of classes and objects start with an upper case letter and use the camel case:

<div class="sample" markdown="1" theme="idea" data-highlight-only>

```kotlin
open class DeclarationProcessor { /*...*/ }

object EmptyDeclarationProcessor : DeclarationProcessor() { /*...*/ }
```

</div>

### Function names
 
Names of functions, properties and local variables start with a lower case letter and use the camel case and no underscores:

<div class="sample" markdown="1" theme="idea" data-highlight-only>

```kotlin
fun processDeclarations() { /*...*/ }
var declarationCount = 1
```

</div>

Exception: factory functions used to create instances of classes can have the same name as the abstract return type:

<div class="sample" markdown="1" theme="idea" data-highlight-only>

```kotlin
interface Foo { /*...*/ }

class FooImpl : Foo { /*...*/ }

fun Foo(): Foo { return FooImpl() }
```
</div>

#### Names for test methods

In tests (and **only** in tests), it's acceptable to use method names with spaces enclosed in backticks.
(Note that such method names are currently not supported by the Android runtime.) Underscores in method names are
also allowed in test code.

<div class="sample" markdown="1" theme="idea" data-highlight-only>

```kotlin
class MyTestCase {
     @Test fun `ensure everything works`() { /*...*/ }
     
     @Test fun ensureEverythingWorks_onAndroid() { /*...*/ }
}
```

</div>

### Property names

Names of constants (properties marked with `const`, or top-level or object `val` properties with no custom `get` function
that hold deeply immutable data) should use uppercase underscore-separated names:

<div class="sample" markdown="1" theme="idea" data-highlight-only>

```kotlin
const val MAX_COUNT = 8
val USER_NAME_FIELD = "UserName"
```

</div>

Names of top-level or object properties which hold objects with behavior or mutable data should use camel-case names:

<div class="sample" markdown="1" theme="idea" data-highlight-only>

```kotlin
val mutableCollection: MutableSet<String> = HashSet()
```

</div>

Names of properties holding references to singleton objects can use the same naming style as `object` declarations:

<div class="sample" markdown="1" theme="idea" data-highlight-only>

```kotlin
val PersonComparator: Comparator<Person> = /*...*/
```

</div>
 
For enum constants, it's OK to use either uppercase underscore-separated names
(`enum class Color { RED, GREEN }`) or regular camel-case names starting with an uppercase first letter, depending on the usage.
   
#### Names for backing properties

If a class has two properties which are conceptually the same but one is part of a public API and another is an implementation
detail, use an underscore as the prefix for the name of the private property:

<div class="sample" markdown="1" theme="idea" data-highlight-only>

```kotlin
class C {
    private val _elementList = mutableListOf<Element>()

    val elementList: List<Element>
         get() = _elementList
}
```

</div>

### Choosing good names

The name of a class is usually a noun or a noun phrase explaining what the class _is_: `List`, `PersonReader`.<commit_msg>chore: Coding Conventions grammar fixes (#1933)<commit_after>---
type: doc
layout: reference
category: Basics
title: Coding Conventions
---

# Coding Conventions

This page contains the current coding style for the Kotlin language.

* [Source code organization](#source-code-organization)
* [Naming rules](#naming-rules)
* [Formatting](#formatting)
* [Documentation comments](#documentation-comments)
* [Avoiding redundant constructs](#avoiding-redundant-constructs)
* [Idiomatic use of language features](#idiomatic-use-of-language-features)
* [Coding conventions for libraries](#coding-conventions-for-libraries)

### Applying the style guide

To configure the IntelliJ formatter according to this style guide, please install Kotlin plugin version
1.2.20 or newer, go to __Settings | Editor | Code Style | Kotlin__, click __Set from...__ link in the upper
right corner, and select __Kotlin style guide__ from the menu.

To verify that your code is formatted according to the style guide, go to __Settings | Editor | Inspections__ and enable
the __Kotlin | Style issues | File is not formatted according to project settings__ inspection. Additional
inspections that verify other issues described in the style guide (such as naming conventions) are enabled by default.

## Source code organization

### Directory structure

In pure Kotlin projects, the recommended directory structure follows the package structure with
the common root package omitted. For example, if all the code in the project is in the `org.example.kotlin` package and its
subpackages, files with the `org.example.kotlin` package should be placed directly under the source root, and
files in `org.example.kotlin.network.socket` should be in the `network/socket` subdirectory of the source root.

> **On the JVM**: In projects where Kotlin is used together with Java, Kotlin source files should reside in the same source root as the Java source files,
and follow the same directory structure: each file should be stored in the directory corresponding to each package
statement.

### Source file names

If a Kotlin file contains a single class (potentially with related top-level declarations), its name should be the same
as the name of the class, with the .kt extension appended. If a file contains multiple classes, or only top-level declarations,
choose a name describing what the file contains, and name the file accordingly.
Use [upper camel case](https://en.wikipedia.org/wiki/Camel_case) with an uppercase first letter (for example, `ProcessDeclarations.kt`).

The name of the file should describe what the code in the file does. Therefore, you should avoid using meaningless
words such as "Util" in file names.

### Source file organization

Placing multiple declarations (classes, top-level functions or properties) in the same Kotlin source file is encouraged
as long as these declarations are closely related to each other semantically and the file size remains reasonable
(not exceeding a few hundred lines).

In particular, when defining extension functions for a class which are relevant for all clients of this class,
put them in the same file where the class itself is defined. When defining extension functions that make sense 
only for a specific client, put them next to the code of that client. Do not create files just to hold 
"all extensions of Foo".

### Class layout

Generally, the contents of a class is sorted in the following order:

- Property declarations and initializer blocks
- Secondary constructors
- Method declarations
- Companion object

Do not sort the method declarations alphabetically or by visibility, and do not separate regular methods
from extension methods. Instead, put related stuff together, so that someone reading the class from top to bottom can 
follow the logic of what's happening. Choose an order (either higher-level stuff first, or vice versa) and stick to it.

Put nested classes next to the code that uses those classes. If the classes are intended to be used externally and aren't
referenced inside the class, put them in the end, after the companion object.

### Interface implementation layout

When implementing an interface, keep the implementing members in the same order as members of the interface (if necessary,
interspersed with additional private methods used for the implementation)

### Overload layout

Always put overloads next to each other in a class.

## Naming rules

Package and class naming rules in Kotlin are quite simple:

* Names of packages are always lower case and do not use underscores (`org.example.project`). Using multi-word
names is generally discouraged, but if you do need to use multiple words, you can either simply concatenate them together
or use camel case (`org.example.myProject`).

* Names of classes and objects start with an upper case letter and use camel case:

<div class="sample" markdown="1" theme="idea" data-highlight-only>

```kotlin
open class DeclarationProcessor { /*...*/ }

object EmptyDeclarationProcessor : DeclarationProcessor() { /*...*/ }
```

</div>

### Function names
 
Names of functions, properties and local variables start with a lower case letter and use camel case and no underscores:

<div class="sample" markdown="1" theme="idea" data-highlight-only>

```kotlin
fun processDeclarations() { /*...*/ }
var declarationCount = 1
```

</div>

Exception: factory functions used to create instances of classes can have the same name as the abstract return type:

<div class="sample" markdown="1" theme="idea" data-highlight-only>

```kotlin
interface Foo { /*...*/ }

class FooImpl : Foo { /*...*/ }

fun Foo(): Foo { return FooImpl() }
```
</div>

#### Names for test methods

In tests (and **only** in tests), it's acceptable to use method names with spaces enclosed in backticks.
(Note that such method names are currently not supported by the Android runtime.) Underscores in method names are
also allowed in test code.

<div class="sample" markdown="1" theme="idea" data-highlight-only>

```kotlin
class MyTestCase {
     @Test fun `ensure everything works`() { /*...*/ }
     
     @Test fun ensureEverythingWorks_onAndroid() { /*...*/ }
}
```

</div>

### Property names

Names of constants (properties marked with `const`, or top-level or object `val` properties with no custom `get` function
that hold deeply immutable data) should use [screaming snake case](https://en.wikipedia.org/wiki/Snake_case) names:

<div class="sample" markdown="1" theme="idea" data-highlight-only>

```kotlin
const val MAX_COUNT = 8
val USER_NAME_FIELD = "UserName"
```

</div>

Names of top-level or object properties which hold objects with behavior or mutable data should use camel case names:

<div class="sample" markdown="1" theme="idea" data-highlight-only>

```kotlin
val mutableCollection: MutableSet<String> = HashSet()
```

</div>

Names of properties holding references to singleton objects can use the same naming style as `object` declarations:

<div class="sample" markdown="1" theme="idea" data-highlight-only>

```kotlin
val PersonComparator: Comparator<Person> = /*...*/
```

</div>
 
For enum constants, it's OK to use either screaming snake case
(`enum class Color { RED, GREEN }`) or upper camel case names, depending on the usage.
   
#### Names for backing properties

If a class has two properties which are conceptually the same but one is part of a public API and another is an implementation
detail, use an underscore as the prefix for the name of the private property:

<div class="sample" markdown="1" theme="idea" data-highlight-only>

```kotlin
class C {
    private val _elementList = mutableListOf<Element>()

    val elementList: List<Element>
         get() = _elementList
}
```

</div>

### Choosing good names

The name of a class is usually a noun or a noun phrase explaining what the class _is_: `List`, `PersonReader`.
{'fraction_non_alphanumeric': 0.07960484384958573, 'fraction_numerical': 0.0020395156150414275, 'mean_word_length': 4.6605339105339105, 'pattern_counts': {'":': 0, '<': 43, '<?xml version=': 0, '>': 45, 'https://': 3, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3821317', 'n_tokens_mistral': 4170, 'n_tokens_neox': 3914, 'n_words': 2074}