Thursday, 25 January 2018

Kotlin: ?: Elvis operator

By using Elvis operator, for any nullable reference 'n', we can say 'If n is not null use it, else use some default value'.

var name = emp?.name ?: "DefaultEmp"

Above statement return employee name, if emp is non-null, else return "DefaultEmp"

Find the below working application.

Test.kt
package com.sample.test

class Department {
 var departmentName: String = ""
 var departmentId: String = ""
}

class Employee {
 var name: String = ""
 var department: Department? = null
}

private fun printEmpDetails(emp: Employee?) {
 var name = emp?.name ?: "DefaultEmp"
 var departmentName = emp?.department?.departmentName ?: "DefaultDept"
 var departmentId = emp?.department?.departmentId ?: "DefaultDept"


 println("name : $name")
 println("departmentName : $departmentName")
 println("departmentId : $departmentId")
 println("\n")
}

fun main(args: Array<String>) {
 var emp1: Employee? = null

 var emp2 = Employee()
 emp2.name = "Chamu"

 var emp3 = Employee()

 var department = Department()
 department.departmentId = "DEP01"
 department.departmentName = "CSC"
 emp3.department = department
 emp3.name = "Krishna"

 printEmpDetails(emp1)
 printEmpDetails(emp2)
 printEmpDetails(emp3)
}

Output

name : DefaultEmp
departmentName : DefaultDept
departmentId : DefaultDept


name : Chamu
departmentName : DefaultDept
departmentId : DefaultDept


name : Krishna
departmentName : CSC
departmentId : DEP01



Previous                                                 Next                                                 Home

No comments:

Post a Comment