首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >改进infix isNullOrEmpty

改进infix isNullOrEmpty
EN

Stack Overflow用户
提问于 2019-01-15 10:30:41
回答 1查看 90关注 0票数 0

我试图通过使用infix来改进一些代码:

工作代码(但有点难看):

代码语言:javascript
复制
fun test (possibleEmptyString: String?, anotherPossibleEmptyString : String?): String {
    var test: String? = possibleEmptyString

    // If null or empty
    if(test!=null && !"".equals(test)) {
        test = anotherPossibleEmptyString
    }

    // If null or empty
    if(test!=null && !"".equals(test)) {
        test = "a known string"
    }

    return test!!
}

我想提高这样的可读性:

代码语言:javascript
复制
fun test (possibleEmptyString: String?, anotherPossibleEmptyString : String?): String {
    return (possibleEmptyString orIfNullOrEmpty anotherPossibleEmptyString orIfNullOrEmpty "a known string")!!
}

infix fun String?.orIfNullOrEmpty(other: String?): String? {
    if (this != null && !"".equals(this)) {
        return this
    }

    return other
}

它可以工作,但我认为它可以改进。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-01-15 10:40:57

它可以简化如下:

代码语言:javascript
复制
infix fun String?.orIfNullOrEmpty(other: String?) = 
    takeUnless { it.isNullOrBlank() } ?: other

您可以使用this (在本例中,可以在this上直接调用takeUnless { },因为扩展),如果它不是空或空,则为other

注意,Kotlin已经有了isNullOrBlank和类似的扩展。

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

https://stackoverflow.com/questions/54197040

复制
相关文章

相似问题

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