如何在Kotlin中的同名扩展函数中调用buildin扩展函数?

时间:2020-10-06 18:24:14

标签: kotlin

kotlin在kotlin.text中具有两个内置扩展功能:

public actual inline fun String.toBoolean()
public actual inline fun String?.toBoolean()

现在我要为toBoolean添加Any?

fun Any?.toBoolean(): Boolean {
    return when(this){
        null -> false
        is Boolean -> this
        is Boolean? -> this

        // Here toBoolean() is this function itself, not kotlin.text.String.toBoolean
        else -> toString().toBoolean()
    }
}

else -> toString().toBoolean()中,toBoolean()函数不是kotlin.text中的同名扩展函数,请参见注释。

我尝试导入kotlin.text.toBoolean或kotlin.text.String.toBoolean,但是没有用。

1 个答案:

答案 0 :(得分:4)

您可以使用其他名称导入要调用的函数,如下所示:

import kotlin.text.toBoolean as stringToBoolean

fun Any?.toBoolean(): Boolean {
    return when(this){
        null -> false
        is Boolean -> this
        is Boolean? -> this
        else -> toString().stringToBoolean()
    }
}

顺便说一句,is Boolean? -> this是多余的支票。