首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在kotlin中调用同名扩展函数中的buildin扩展函数?

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

Stack Overflow用户
提问于 2020-10-07 02:24:15
回答 1查看 28关注 0票数 0

kotlin在kotlin.text中有两个内置的扩展函数

代码语言:javascript
运行
复制
public actual inline fun String.toBoolean()
public actual inline fun String?.toBoolean()

现在,我想为Any?添加toBoolean

代码语言:javascript
运行
复制
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,但不起作用。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-07 02:36:45

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

代码语言:javascript
运行
复制
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是一个冗余检查。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64231710

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档