kotlin在kotlin.text中有两个内置的扩展函数
public actual inline fun String.toBoolean()
public actual inline fun String?.toBoolean()现在,我想为Any?添加toBoolean
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,但不起作用。
发布于 2020-10-07 02:36:45
您可以使用不同的名称导入要调用的函数,如下所示:
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是一个冗余检查。
https://stackoverflow.com/questions/64231710
复制相似问题