In order to detail the first use-case, let’s consider any function defined in the String class. Here’s how one would call that function on a nullable type:

var myNullableString : String ? = null // Do something on myNullableString // At this point, myNullableString can be null or not val capitalized : String ? = myNullableString ?. capitalize ()

Because myNullableString might be null , it’s not valid to directly call the function with the standard . operator: the compiler will flag such code as invalid and prevent compilation. To fix the compilation error, one should use the provided safe call operator ?. .

Thanks to the latter, at runtime, if the variable is not null , everything will work out as expected. If it is, capitalized will be null instead of throwing an exception. This might be enough if one accepts to have null values propagated along the flow, but what if not? Wouldn’t it be great if one could provide a default value if the value was null , just as with Java’s Optional.getOrElse() ? Java’s approach is to encapsulate the logic in a class. Otherwise, we would need a static function. In Kotlin, we can write top-level functions:

fun orElse ( string : String ?, default : String ) = string ?: default

However, this can also be written in a different way. One must remember that extension functions are just syntactic sugar for static functions. For that reason, it’s possible to write extension functions on nullable types. Let’s rewrite the above functions with that in mind:

fun String ?. orElse ( default : String ) = this ?: default

It’s now safe to call the orElse() extension function on nullable types:

val nonNull : String = myNullableString . orElse ( "" )