可为空的接收者

需要注意的是扩展可以定一一个空的接收器类型。这样的扩展即使在对象变量为空时都可以调用,并且可以在函数的主体检查this == null。这样允许你在Kotlin中调用toString()方法,而不需要进行空检查。

fun Any?.toString(): String {
    if (this == null) return "null"
    // after the null check, 'this' is autocast to a non-null type, so the toString() below
    // resolves to the member function of the Any class
    return toString()
}

results matching ""

    No results matching ""