Sunday, 24 December 2017

Kotlin: Constructors

Kotlin classes have a primary constructor and one or more secondary constructors. Constructors are defined using constructor keyword.

Primary Constructor
Primary constructor is defined as part of the class header.

Ex
class Employee constructor(fName: String, lName: String) {
         ....
         ....
}

Employee.kt
class Employee constructor(fName: String, lName: String) {
 init{
  println("fName : $fName, lName : $lName")
 }
}

Main.kt
fun main(args: Array<String>) {
 var emp1 = Employee("Hareesh", "Seeram")
}
Output
fName : Hareesh, lName : Seeram

init{} is equivalent to the initializer block of java, it is used to place the object initialization code. This block is called on every object instantiation.

You can omit the constructor keyword while defining primary constructor, if the constructor do not have any modifier (or) annotation associated with it.


Employee.kt
class Employee (fName: String, lName: String) {
 init{
  println("fName : $fName, lName : $lName")
 }
}

Defining member variables as part of primary constructor
If you add the keyword ‘var’/’val’ to the type parameter in primary constructor, it creates a field in class.


Main.kt
class Employee(var firstName: String, var lastName: String) {

}

fun main(args: Array<String>) {
 var emp1 = Employee("Hareesh", "Seeram")

 println("firstName : ${emp1.firstName}, lastName : ${emp1.lastName}")
}

Output

firstName : Hareesh, lastName : Seeram

In the above snippet, I defined firstName and lastName fields as part of primary constructor




Previous                                                 Next                                                 Home

No comments:

Post a Comment