Safe call operator (?.)

Kotlin has a syntax that replaces null checks. This is called the safe call or safe call operator:

    num?.toFloat()

The preceding line returns the float conversion of the number if it is not null and null otherwise. While dealing with complex objects often we have chain calls that result in a lot of nested if. For example, the following nested if blocks:

    if(linkedInUser!=null) {      if (linkedInUser.siteStandardProfileRequest != null) {        if (imageView != null) {                        imageView.show(linkedInUser.siteStandardProfileRequest.url);        }      }    }

This can be converted into one line, which is:

    imageView?.show(linkedInUser?.siteStandardProfileRequest?.url)

Get Kotlin Blueprints now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.