Thursday, 28 December 2017

Kotlin: Passing default values to primary constructor

You can pass default values to the primary constructor.

Ex:
class Employee(var firstName: String = "Krishna", var lastName: String = "Gurram") {

}

Above snippet defines a primary constructor to the class Employee, with default values.

var emp1 = Employee()
Since we do not pass any arguments to the constructor, firstName and lastName are initialized with default values. 'firstName' is initialized with 'Krishna' and lastName is initialized with 'Gurram'

var emp2 = Employee("Rachit")
Since we passed only first argument, 'firstName' is assigned with value 'Rachit' and 'lastName' is assigned with value 'Gurram'

var emp3 = Employee("Shwetha", "kam")
'firstName' is assigned with value 'Shwetha' and 'lastName' is assigned with value 'Kam'.    

ConstructorDemo.kt

class Employee(var firstName: String = "Krishna", var lastName: String = "Gurram") {

}

fun printEmployee(emp: Employee) {
 println("firstName : ${emp.firstName}, lastName : ${emp.lastName}")
}

fun main(args: Array<String>) {
 var emp1 = Employee()
 var emp2 = Employee("Rachit")
 var emp3 = Employee("Shwetha", "kam")

 printEmployee(emp1)
 printEmployee(emp2)
 printEmployee(emp3)

}

Output

firstName : Krishna, lastName : Gurram
firstName : Rachit, lastName : Gurram
firstName : Shwetha, lastName : kam


Previous                                                 Next                                                 Home

No comments:

Post a Comment