Saturday, 30 December 2017

Kotlin: How to create Object

Unlike Java, 'new' keyword is not required to define an object.

Syntax
var objectName  = ClassName(arguments)

Ex
var emp1 = Employee("Shwetha")
var emp2 = Employee("Krishna", "G")

ConstructorDemo.kt

class Employee {

 var firstName: String = ""
 var lastName: String = ""

 constructor(fName: String) {
  this.firstName = fName
  this.lastName = fName
 }

 constructor(fName: String, lName: String) {
  this.firstName = fName
  this.lastName = lName
 }
}

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

fun main(args: Array<String>) {
 var emp1 = Employee("Shwetha")
 var emp2 = Employee("Krishna", "G")

 printEmployee(emp1)
 printEmployee(emp2)

}

Output

firstName : Shwetha, lastName : Shwetha
firstName : Krishna, lastName : G



Previous                                                 Next                                                 Home

No comments:

Post a Comment