Kotlin Constructors: In this tutorial, you will learn about constructors in Kotlin (both primary and secondary constructors) just as initializer blocks with the assistance of examples.
In Kotlin, constructor is a square of code like technique. Constructor is pronounced with a similar name as the class followed by parenthesis ‘()’. Constructor is used to introduce the variables at the hour of object creation.
A constructor is a compact method to introduce class properties.
It is an extraordinary part of work that is considered when an object is started up (created). Nonetheless, how they work in Kotlin is somewhat extraordinary.
In Kotlin, there are two constructors:
• Primary constructor – succinct approach to instate a class
• Secondary constructor – allows you to put extra instatement rationale
In this article, you will learn-
Primary Constructor
The primary constructor is important for the class header. Here’s an example:
class Person(val firstName: String, var age: Int) { // class body }
The block of code surrounded by parentheses is the primary constructor: (val firstName: String, var age: Int).
The constructor pronounced two properties: firstName (read-just property as it’s proclaimed using watchword val) and age (read-write property as it is announced with catchphrase var).
Example: Primary Constructor
fun main(args: Array<String>) { val person1 = Person("Sohail", 25) println("First Name = ${person1.firstName}") println("Age = ${person1.age}") } class Person(val firstName: String, var age: Int) { }
At the point when you run the program, the output will be:
First Name = Sohail Age = 25
At the point when the object of Person class is created, “Sohail” and 25 values are passed as though Person is a function.
This introduces firstName and age properties of person1 object to “Sohail” and 25 respectively.
There are other ways of using primary constructors.
Primary Constructor and Initializer Blocks
The primary constructor has a constrained syntax, and can’t contain any code.
To put the initialization code (not just code to instate properties), an initializer block is used. It is prefixed with init catchphrase. Let’s modify the above example with initializer block:
fun main(args: Array<String>) { val person1 = Person("sohail", 25) } class Person(fName: String, personAge: Int) { val firstName: String var age: Int // initializer block init { firstName = fName.capitalize() age = personAge println("First Name = $firstName") println("Age = $age") } }
At the point when you run the program, the output will be:
First Name = Sohail Age = 25
Here, parameters fName and personAge inside the parenthesis acknowledge values “Sohail” and 25 respectively when the person1 object is created. Notwithstanding, fName and personAge are used without using var or val, and are not properties of the Person class.
The Person class has two properties firstName, and age are announced.
When person1 object is created, code inside initializer block is executed. The initializer block not only initializes its properties but also prints them.
Here is another way to perform the same task:
fun main(args: Array<String>) { val person1 = Person("sohail", 25) } class Person(fName: String, personAge: Int) { val firstName = fName.capitalize() var age = personAge // initializer block init { println("First Name = $firstName") println("Age = $age") } }
To recognize the constructor parameter and property, various names are used (fName and firstName, and personAge and age). It’s more normal to use _firstName and _age rather than totally different name for constructor parameter. For instance:
class Person(_firstName: String, _age: Int) { val firstName = _firstName.capitalize() var age = _age // initializer block init { ... .. ... } }
Default Value in Primary Constructor
You can provide default value to constructor parameters (like providing default arguments to functions). For instance:
fun main(args: Array<String>) { println("person1 is instantiated") val person1 = Person("sohail", 25) println("person2 is instantiated") val person2 = Person("salman") println("person3 is instantiated") val person3 = Person() } class Person(_firstName: String = "UNKNOWN", _age: Int = 0) { val firstName = _firstName.capitalize() var age = _age // initializer block init { println("First Name = $firstName") println("Age = $age\n") } }
At the point when you run the program, the output will be:
First Name = Sohail Age = 25 person2 is instantiated First Name = Salman Age = 0 person3 is instantiated First Name = UNKNOWN Age = 0
Kotlin Secondary Constructor
In Kotlin, a class can likewise contain at least one or more secondary constructors. They are created using constructor catchphrase.
Secondary constructors are not that normal in Kotlin. The most widely recognized use of secondary constructor comes up when you need to expand a class that gives numerous constructors that introduce the class in different ways.
Here’s the manner by which you can create a secondary constructor in Kotlin:
class Log { constructor(data: String) { // some code } constructor(data: String, numberOfData: Int) { // some code } }
Here, the Log class has two secondary constructors, however no primary constructor.
You can expand the class as:
class Log { constructor(data: String) { // code } constructor(data: String, numberOfData: Int) { // code } } class AuthLog: Log { constructor(data: String): super(data) { // code } constructor(data: String, numberOfData: Int): super(data, numberOfData) { // code } }
Here, constructors of the determined class AuthLog calls the comparing constructor of the base class Log. For that, super() is used.
In Kotlin, you can likewise call a constructor from another constructor of a similar class (like in Java) using this().
class AuthLog: Log { constructor(data: String): this(data, 10) { // code } constructor(data: String, numberOfData: Int): super(data, numberOfData) { // code } }
Example: Kotlin Secondary Constructor
fun main(args: Array<String>) { val p1 = AuthLog("Bad Password") } open class Log { var data: String = "" var numberOfData = 0 constructor(_data: String) { } constructor(_data: String, _numberOfData: Int) { data = _data numberOfData = _numberOfData println("$data: $numberOfData times") } } class AuthLog: Log { constructor(_data: String): this("From AuthLog -> " + _data, 10) { } constructor(_data: String, _numberOfData: Int): super(_data, _numberOfData) { } }
At the point when you run the program, the output will be:
From AuthLog -> Bad Password: 10 times
Note: The secondary constructor should instate the base class or representative to another constructor (like in the above example) if the class has no primary constructor.
Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.