Updated April 6, 2023
Introduction to Kotlin Constructors
A constructor is a special member function which is invoked when a class object is generated primarily for the initialization of variables or properties. A class needs to have a constructor and if we don’t declare a constructor then a default constructor is created by the compiler.
Types of Kotlin Constructors
There are two types of Constructor:
- Primary Constructor: It is a concise way to initialize a class.
- Secondary Constructor: It allows you to put additional initialization logic.
A Kotlin class can have a limit of one main constructor, and one or more secondary builders. The main builder initializes the class while using the secondary builder to initialize the class and add some additional logic.
Examples to Implement of Kotlin Constructors
Below are the examples of Kotlin Constructors:
Example #1 – Primary Constructor
Primary Constructor are initialized in the class header, using the constructor Keyword. Here is a program using Primary Constructor.
Code:
fun main(args: Array<String>)
{
val add = Add (3,7)
println("Sum will be: ${add.c}")
}
//now the Primary constructor will be used
class Add constructor(a: Int, b:Int)
{
var c = a+b;
}
Output:
Explanation: If we create the add object for the class then the values 3 and 7 will pass to the constructor.
3 The Constructor parameters a and b initialize respectively with parameters 3 and 7. The vector locale c includes the number of variables. In the primary, we use ${add.c} to access contractor properties.
Example #2
Primary Constructor and Initializer Blocks. The primary constructor has a syntax that is limited and cannot contain any code it. So to insert the initialization code an initializer block is used with init, example:
Code :
fun main(args: Array<String>) {
val person1 = NAme("kotlin", 31)
}
class NAme(fName: String, yourAge: Int) {
valnewName: String
var age: Int
// initializer block – This block initialize the code written in the constructor
init {
newName= fName.capitalize()
age = yourAge
println("First Name = $newName")
println("Age = $age")
}
}
Output:
Explanation: In the above program we have used 2 parameters Name andyourAgeinside the parenthesis which accepts the values kotlin and 31 respectively when person1 object is created. HoweverfName and personAgeare used without initialization like var and val and they both are also not properties of the Person class.
And moreover, there is a function called uppercase which changes the character value from lower case to uppercase.
Example #3 – Secondary Constructor
As explained before, Kotlin will have one or two side builders. Secondary constructors allow the initialization of variables and also allow the class to be given any rationale. They are prefixed with the keyword for the constructor.
Kotlin allows the creation of your class of one or more secondary builders. This secondary builder is generated using the keyword”constructor”. It is required whenever you want to create more than one builder in Kotlin or whenever you want to include more logic in the primary builder and you can’t do that because some other class can call the primary constructor. below is the example:
Code:
fun main(args: Array<String>) {
valZambo = Zambo ("Kotlin Learner ", 31)
print("${Zambo.message}"+"${ Zambo.firstName}"+
"Welcome to Kotlin Constructor, Here is your Age-${ Zambo.age}")
}
class Zambo (valfirstName: String, var age: Int) {
val message: String = "Hello! "
constructor(name : String , age :Int ,message :String):this(name,age) {
}
}
Output:
Explanation: In the above program values have been declared under Zambo and then used inside the code which in turn prints the output by concatenating the different variables and values inside the code.
Example #4
Let’s see a few more examples of both Primary and Secondary Constructor in Kotlin:
Code :
fun main(args: Array<String>) {
employeeID(2040050223, "Java")
employeeID(2040050228,"Kotlin",1500000.9)
}
class employeeID {
constructor (NEWemp_id :Int, NEWemp_name: String ) {
var id: Int = NEWemp_id
var name: String = NEWemp_name
print("The Employee id is: $id, ")
println("Name of the Employee: $name")
println()
}
constructor (NEWemp_id :Int, NEWemp_name: String ,NEWemp_salary : Double) {
var id: Int = NEWemp_id
var name: String = NEWemp_name
varsalary : Double = NEWemp_salary
print("The Employee id is: $id, ")
print("Name of the Employee: $name, ")
println("The salary of the Employee: $salary")
}
}
Output :
Explanation: The above program uses two employee IDs and constructors to get the details like employee name, employee id, and salary of one of the employees.
Example #5
Code:
//main function – This defines the main function
fun main(args: Array<String>)
{
Add(60,90)
}
class Add {
// calling another secondary using this
constructor(a:Int, b:Int) : this(a,b,85) {
varsumoftwo = a + b
println("The sum of the above two number 60 and 90 is: $sumoftwo ")
}
// this executes first
constructor(a:Int, b:Int, c:Int) {
varsumofthree= a + b + c
println("The sum of three numbers 60,90 and 85 is: $sumofthree ")
}
}
Output :
Explanation: To above program explains the use of constructor inside the constructor, here we have two constructors which are typing the value of the addition of two numbers in the first constructor and the other is giving the value of three numbers in the second constructor. The above program also explains that initialization happens separately in Kotlin constructor where the values initialized can be reused in another constructor just by calling the function.
Conclusion
In the above article, we discussed and learned about Kotlin Constructor and various ways of creating constructors and different uses of the primary and secondary constructors. You can also use a constructor in different ways according to your use as the main code is written inside the constructor and the values are initialized from later. We also learned that the primary constructor uses init block to carry the execution where the initialization of variables and values takes place, while in the case of a secondary constructor, then you have to call Primary Constructor in a different form.
Recommended Article
This is a guide to Kotlin Constructors. Here we discuss the Introduction and types of Kotlin Constructors along with examples and code implementation. You can also go through our other suggested articles to learn more –