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,但是没有用。
答案 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
是多余的支票。