Constructors

The constructor keyword defines a constructor of class.

primary constructor

The constructor specified after the class name is called the primary constructor.

  1. if the primary constructor does not have any annotations or visibility modifiers, the constructor keyword can be omitted
  2. if the primary constructor is completely omitted, the class will have an empty primary constructor
  3. you can declare properties from the primary constructor
  4. you can initialize class properties with parameters of the primary constructor
class MyCls{ /*...*/ }
class MyCls1 constructor(param: String) { /*...*/ }
class MyCls2(param: String="somevalue") { /*...*/ }
class MyCls3(var field1: String) { /*...*/ }
class MyCls4(var param: String) { var field1=param }

The init block defines a body of primary constructor.

class MyCls { 
    init {
        // do something
    }
}

secondary constructors

Constructors specified within class body are called secondary constructors.

Each secondary constructor needs to delegate to the primary constructor, either directly or indirectly through another secondary constructor(s). Even if a class does not have a primary constructor, the delegation still happens implicitly.

class MyCls(param: String) { 

    // secondary constructor
    constructor(param: String, param2: String) {/*...*/}
} 

class MyCls1(param: String, param2: String) { 

    // delegation to the primary constructor
    // although in this case we can use the default values in the primary constructor
    constructor(): this("some string", "some other string") {/*...*/} 
} 

Additionally you can override the () operator of companion object. This is useful for inline classes.

value class Demo(val x: Double = 0.0) {
    // constructor(arg: Int) : this(arg.toDouble())

    companion object {
        operator fun invoke(arg: Int) = Demo(arg.toDouble())
    }
}

// usage: var demo = Demo(2)