liveBook · Manning

Constructor parameter

As explained in Kotlin in Action, 2E

A constructor parameter is a parameter declared by a Kotlin constructor and optionally promoted to a property.

A constructor parameter supplies values when a Kotlin object is created. Prefixing it with val or var also promotes it to a property, keeping simple class declarations compact. section 4.2.1

class User(val nickname: String)

This compact declaration accepts a nickname and exposes it as a read-only property. section 4.2.1

Default and named arguments

class User( val nickname: String, val isSubscribed: Boolean = true ) User("Alice") User("Bob", false) User("Carol", isSubscribed = false) A parameter can therefore provide a default value, accept positional input, or be selected by name. section 4.2.1

Use an explicit form when initialization needs more structure:

  • Declare a parameter without val or var when it only supplies initialization data. section 4.2.1
  • Refer to primary-constructor parameters from property initializers and initializer blocks. section 4.2.1
  • Pass constructor parameters to a superclass when declaring a subclass. section 4.2.1

How Kotlin in Action, 2E covers it

How deep it goes
Explains concise and explicit declarations, initializer blocks, property promotion, defaults, named arguments, inheritance, and private constructors.
Examples
Demonstrates User declarations, nickname initialization, subscription defaults, named calls, subclass construction, and private constructors.
What it assumes
Assumes basic Kotlin class and object syntax while teaching primary-constructor parameters and initializer blocks explicitly.
What you can do after
Apply it through Kotlin primary-constructor syntax to create initialized objects and expose selected constructor values as properties.
How it connects
Connects constructor parameters to primary constructors, properties, initializer blocks, default arguments, named arguments, and superclass construction.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.