A primary constructor is the concise constructor declared in a Kotlin class header, outside the class body. It specifies creation-time parameters and can turn those parameters directly into properties. Use it for the usual case; use initializer blocks when creation needs additional logic. section 4.2 section 4.2.1
Declare constructor properties in the header
```kotlin class User(val nickname: String) ``` `nickname` is both a constructor parameter and a read-only property. This replaces a separate property declaration and assignment in the class body. section 4.2.1
Expand the compact form only when needed:
- Write `constructor` explicitly when the primary constructor has annotations or a visibility modifier; otherwise it may be omitted. section 4.2.1
- Reference primary-constructor parameters from property initializers and `init` blocks. An `init` block runs when an instance is created and holds logic the constructor syntax cannot contain. section 4.2.1
- Give constructor properties default values, then call the class with positional or named arguments. section 4.2.1
- Pass a primary-constructor argument to a superclass constructor after `:` when extending a class. section 4.2.1
Primary constructors keep ordinary initialization close to the class name. Kotlin distinguishes them from secondary constructors in the class body. Prefer default parameter values over secondary constructors merely to provide overloaded defaults; secondary constructors remain useful when interoperating with Java framework classes that expose multiple constructors. section 4.2 section 4.2.2
The primary constructor also defines an important boundary for data classes: generated `equals`, `hashCode`, and `toString` use properties declared there. Properties declared only in the body are excluded from equality and hash-code calculation. section 4.3.2
class User constructor(_nickname: String) { #1
val nickname: String
init { #2
nickname = _nickname
}
}
Compare the expanded form: a constructor parameter is assigned to a separately declared property inside an `init` block. The compact header form expresses the same simple initialization directly. section 4.2.1
