
上QQ阅读APP看书,第一时间看更新
Extension functions on null values
Kotlin even supports extension functions on null values. In those situations, the this reference will contain the null value, and so, Any function that doesn't safely handle null references would throw a null pointer exception.
This functionality is how the equals function can be overloaded to provide safe usage to even null values:
fun Any?.safeEquals(other: Any?): Boolean { if (this == null && other == null) return true if (this == null) return false return this.equals(other) }
This function can be called from both null and non-null values, and the Kotlin compiler will handle both cases for you.