Kotlin Constructors

A constructor is a special member that have the same name as the class name. Constructor method is automatically called when a new object is created, there is no need to call it explicitly. It initializes object of a class.

Types of Constructors in Kotlin

There are two types of constructors in Kotlin.

  • Primary Constructor
  • Secondary Constructor

Primary Constructor

A class in kotlin can have only one primary constructor. It is used to initialize the class and declared at class header. In this the block of the code is surrounded by parentheses.

class Account(var acct_no: Int, var acc_name: String) {
	// body
}

In the above code, there are two properties acct_no and acc_name.


Secondary Constructor

Every code in the initialization block becomes part of the primary constructor. The code of all initializer blocks is executed before the secondary constructor body. Delegation to the primary constructor happens as the first statement of a secondary constructor.

class Account {
	var id: Int
	var name: String
	constructor(id: Int, name: String) {
		this.id = id
		this.name = name
	}
}
fun main(args : Array<String>)  { 
	var acc = Account(11, 'Jorz')
	println("Id = ${ acc.id}")  
	println("Name = ${ acc.name}")  
}
Output

Id = 11
Name = Jorz


Initialization Block

A class in Kotlin can have one or more secondary constructor. They are created using constructor keyword. If the class has a primary constructor, each secondary constructor needs to delegate to the primary constructor, either directly or indirectly through another secondary constructor(s). Delegation to another constructor of the same class is done using the this keyword.

class Account {
    init {
        println("This is init block.")
    }
    constructor(i: Int) {
        println("Number is $i")
    }
}
fun main(args : Array<String>)  { 
    var acc = Account(10)
}
Output
This is init block.
Number is 10






Read more articles