Nullable Receivers

Extensions on Nullable Types

An extension can be declared on a nullable type (String?). Then it can be called on null without ?., and you handle null inside. The standard isNullOrBlank() and orEmpty() work this way.

Example

fun String?.orDash(): String = if (this.isNullOrBlank()) "-" else this

fun Int?.orZero() = this ?: 0

fun main() {
    val nickname: String? = null
    val city: String? = "Vizag"
    println(nickname.orDash())
    println(city.orDash())
    val stock: Int? = null
    println(stock.orZero() + 5)
}

Output

-
Vizag
5

Companion Object Extensions

Example

If a class has a companion object, you can add "static-like" functions to it.

class Temperature(val celsius: Double) {
    companion object
}

fun Temperature.Companion.fromFahrenheit(f: Double) = Temperature((f - 32) * 5 / 9)

fun main() {
    val t = Temperature.fromFahrenheit(98.6)
    println("%.1f C".format(t.celsius))
}

Output

37.0 C