Kotlin secondary (auxiliary) class constructors (syntax, examples)

This page is a work in progress, but if you need to create a secondary class constructor in Kotlin, I hope it’s helpful.

Secondary class constructor rules

First, here are a few rules to know about Kotlin secondary class constructors:

  • A class can have zero or more secondary class constructors
  • A secondary constructor must call the primary constructor; this can happen by directly calling the primary constructor, or by calling another secondary constructor that calls the primary constructor
  • You call other constructors of the same class with the this keyword

Kotlin secondary class constructor example (syntax)

Next, here’s an example of Kotlin secondary class constructors:

class Pizza constructor (
    var crustSize: String,
    var crustType: String,
    val toppings: MutableList<String> = mutableListOf()
) {

    // secondary constructor (no-args)
    constructor() : this("small", "thin")

    // secondary constructor (2-args)
    constructor(crustSize: String, crustType: String) : this(crustSize, crustType, mutableListOf<String>())

    override fun toString(): String = "size: ${crustSize}, type: ${crustType}, toppings: ${toppings}"

}

That example is a little convoluted, so I’ll try to come up with a better one, but it does show the proper syntax for the primary and secondary Kotlin constructors.

Here’s a main function you can use to test those constructors:

fun main(args: Array<String>) {

    var p = Pizza()
    println(p)

    p = Pizza("large", "thick")
    println(p)

    p = Pizza("large", "thick", mutableListOf("cheese", "pepperoni"))
    println(p)

}

And here’s what the output of that main function looks like in an IDE:

size: small, type: thin, toppings: []
size: large, type: thick, toppings: []
size: large, type: thick, toppings: [cheese, pepperoni]

As that output shows, the primary and secondary constructors all work as you expect.