Kotlin – Constructors

Kotlin – Constructors

In this section, we will find out about constructors in Kotlin. Kotlin has two kinds of constructor – one is the essential constructor and the other is the optional constructor. One Kotlin class can have one essential constructor, and at least one auxiliary constructor. Java constructor introduces the part factors, be that as it may, in Kotlin the essential constructor instates the class, though the optional constructor incorporates some additional rationale while introducing the equivalent. The essential constructor can be proclaimed at class header level as appeared in the accompanying model.

class Person(val firstName: String, var age: Int) {
// class body
}

In the above model, we have announced the essential constructor inside the bracket. Among the two fields, first name is perused just as it is pronounced as “val”, while the field age can be altered. In the accompanying precedent, we will utilize the essential constructor.

fun main(args: Array<String>) {
val person1 = Person("softwarelogy.com", 15)
println("First Name = ${person1.firstName}")
println("Age = ${person1.age}")
}
class Person(val firstName: String, var age: Int) {
}

The above bit of code will naturally introduce the two factors and give the accompanying yield in the program.

First Name = softwarelogy.com
Age = 15

As referenced before, Kotlin permits to make at least one auxiliary constructors for your class. This optional constructor is made utilizing the “constructor” catchphrase. It is required at whatever point you need to make more than one constructor in Kotlin or at whatever point you need to incorporate more rationale in the essential constructor and you can’t do that on the grounds that the essential constructor might be called by some different class. Investigate the accompanying precedent, where we have made an auxiliary constructor and are utilizing the above guide to execute the equivalent.

fun main(args: Array<String>) {
val HUman = HUman("softwarelogy.com", 25)
print("${HUman.message}"+"${HUman.firstName}"+"Welcome to the example of Secondary constructor, Your Age is-${HUman.age}")
}
class HUman(val firstName: String, var age: Int) {
val message:String ="Heyyo > "
constructor(name : String , age :Int ,message :String):this(name,age){
}
}

Any number of auxiliary constructors can be made, be that as it may, those constructors should call the essential constructor straightforwardly or in a roundabout way.

The above piece of code will yield the following output in the browser.

Heyyo > softwarelogy.comWelcome to the example of Secondary constructor, Your Age is-25

Leave a Reply

Your email address will not be published. Required fields are marked *