Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 134 ยท Classes and Objects

Constructors

Learn Kotlin constructors: the primary constructor, default and named arguments, secondary constructors with this(), init order, private constructors and factory functions, with runnable code.

A constructor is the code that turns a request like Point(3, 4) into a fully formed object. Whatever a constructor does, it must end with an object that is valid and ready to use. Kotlin splits constructors into two kinds: one primary constructor, written in the class header, and any number of secondary constructors, written in the body. Most classes need only the first.

This lesson explains both, shows how default and named arguments replace most overloads, spells out the exact order in which initialization runs (the source of many subtle bugs), and ends with private constructors and factory functions for classes that need control over how they are created. It builds on Classes and Properties.

The primary constructor

The primary constructor sits right after the class name. Parameters marked val or var become properties; others are plain parameters that exist only while the object is being built.

Kotlin Primary constructor and property promotion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

pages is a plain constructor parameter: the property initializer isLong can read it (initializers and init blocks may use constructor parameters), but a normal member function could not. Marking a parameter val or var is called property promotion, and it saves the three-step dance of declaring a field, a parameter and an assignment.

If you want modifiers on the constructor, such as a visibility or an annotation, the constructor keyword becomes mandatory: class Token private constructor(val value: String).

Default values and named arguments

Where other languages write four overloaded constructors, Kotlin writes one with defaults. Callers can then skip parameters and name the ones they pass:

Kotlin Defaults replace overloads

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The five lines print http://localhost:8080, http://example.org:8080, http://localhost:9000, https://example.org:8080 and https://api.test:443. Named arguments may come in any order, and they make boolean arguments readable: Server(secure = true) is clearer than Server(true). See Default and Named Arguments for the function version of this feature, including the @JvmOverloads annotation for Java callers.

The trailing comma after the last parameter is allowed in Kotlin 1.4 and later; it makes diffs cleaner when you add a parameter.

init blocks and the order of initialization

When you create an object, Kotlin runs these steps in order:

  1. The arguments are evaluated and passed to the constructor.
  2. If there is a superclass, its constructor runs first (see Inheritance).
  3. Property initializers and init blocks of this class run, top to bottom in source order.
  4. If the call came through a secondary constructor, the body of that secondary constructor runs last.

You can watch the order:

Kotlin Watching the initialization order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

For Child("x") the output is Base init: X, property initializer: first, init block A, label=x, property initializer: second, init block B. For Child() the same five lines appear but with DEFAULT and label=default, followed by secondary constructor body. The init block B sits below the secondary constructor in the source, yet it still runs before the secondary body: initialization code always belongs to the primary path.

The classic bug in this area is calling an overridable member from init or from a base class constructor. The base class constructor runs while the child's properties still hold their default values. You will see this in Inheritance: do not call open members from constructors.

Secondary constructors

A secondary constructor is declared with the constructor keyword in the class body. If the class has a primary constructor, every secondary constructor must delegate to it, directly or through another secondary, with this(...):

Kotlin Secondary constructors delegating with this

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The three lines print 21.5 C, 36.7 C and 37.0 C. The compiler picks the constructor by argument type (Double, Int, String). Secondary constructors are the right tool when the inputs are of different kinds. When they differ only by missing values, use defaults.

Forgetting the delegation is a compile error:

Kotlin Missing delegation (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler complains: main.kt:2:5: error: primary constructor call expected. Fix it with constructor() : this("unknown").

A class without a primary constructor may have only secondary ones, and each calls super(...) or none. That style shows up when extending Java classes or Android views; in ordinary code a primary constructor is almost always better.

Validating in the constructor

A constructor's job includes refusing bad input. Put the checks in an init block (or in a property initializer) with require:

Kotlin Validation with require (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first two lines are 40% and caught: percentage must be 0..100 but was 140. The last call is not caught, so the program ends with Exception in thread "main" java.lang.IllegalArgumentException: percentage must be 0..100 but was 150 and a stack trace pointing into the init block. Failing early, at creation time, means that any Percentage you hold is guaranteed to be valid. This is the heart of good class design: make illegal states unrepresentable.

Private constructors and factory functions

Sometimes you do not want callers to use the constructor directly: you need to validate, cache, choose among subclasses or give the creation a meaningful name. Make the constructor private and expose factory functions in a companion object:

Kotlin A private constructor with named factories

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The prints are 180s, 90s, 120s and null. parse can return null for bad input, which a constructor never can (a constructor always returns an object or throws). Writing Duration(5) from main would not compile: error: cannot access 'constructor(seconds: Long): Duration': it is private in 'Duration'. Many standard library types work this way; for example listOf and mutableListOf are factory functions, not constructors.

A related trick is a top-level function with the same name as the class, which looks like a constructor to callers but can return a subtype or do extra work. The standard library's List(5) { it * 2 } is exactly that.

Constructing with side effects: keep it light

A constructor should assign state and check invariants. Avoid heavy work (network, files, long computations) in constructors and init blocks:

  • It makes object creation slow and hides costs from callers.
  • Exceptions from I/O are surprising in a constructor.
  • Tests become harder because you cannot create the object without the side effect.

Pass dependencies in as parameters, and put the real work in a function you call afterwards, or compute it lazily (see by lazy in Delegation).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does adding val to a primary-constructor parameter do?

    val and var in the primary constructor promote the parameter to a property. Plain parameters exist only during construction.
  2. 2. A class has a primary constructor. What must every secondary constructor do?

    Without delegation the compiler reports 'primary constructor call expected'. Delegation guarantees the primary initialization always runs.
  3. 3. In what order do init blocks and property initializers run?

    They are interleaved exactly as written. A secondary constructor body runs after all of them.
  4. 4. When is a factory function better than a public constructor?

    A constructor must return a new instance or throw. A factory can return null or a Result, hide the real type and have names such as ofMinutes.
  5. 5. Which call prints https://localhost:8080 for class Server(val host: String = "localhost", val port: Int = 8080, val secure: Boolean = false) whose toString builds the URL?

    A named argument lets you set only the third parameter and keep the other defaults. Server(true) would not compile because the first parameter is a String.

Summary

  • The primary constructor lives in the class header; val/var parameters become properties, other parameters are visible only to initializers and init blocks.
  • Default and named arguments replace most overloaded constructors.
  • Initialization order is: superclass constructor, then property initializers and init blocks in source order, then the secondary constructor body.
  • Secondary constructors must delegate to the primary with this(...); use them when inputs are of different kinds.
  • Validate with require in init, so that an invalid object never exists.
  • Use a private constructor plus factory functions when creation needs validation, naming or a nullable result.

Next: Visibility Modifiers