Thursday 25 January 2018

Kotlin: ?.: Safe call operator: handle nullable types

In my previous post, I explained nullable types. In this post, I am going to explain, how can we handle nullable types using ?. (Safe call operator).

Ex:
emp?.name

?. (Safe call operator) return employee name if the emp is not null, otherwise null.

Safe calls are used in chains, for example, below statements return the deparementName and departmentId by using safe call operator.

         var departmentName = emp?.department?.departmentName
         var departmentId = emp?.department?.departmentId

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
 var departmentName = emp?.department?.departmentName
 var departmentId = emp?.department?.departmentId


 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 : null
departmentName : null
departmentId : null


name : Chamu
departmentName : null
departmentId : null


name : Krishna
departmentName : CSC
departmentId : DEP01




Previous                                                 Next                                                 Home

No comments:

Post a Comment