我正在尝试通过使用infix改进一些代码:
工作代码(但有点丑...):
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!!
}
我想提高可读性:
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
}
它可以工作,但我认为可以改善
答案 0 :(得分:3)
可以这样简化:
infix fun String?.orIfNullOrEmpty(other: String?) =
takeUnless { it.isNullOrBlank() } ?: other
如果不为null或为空,则采用this
(在此情况下,takeUnless { }
可以直接在this
上调用,因为扩展名),否则为other
。
请注意,Kotlin已经具有isNullOrBlank
和类似名称的扩展名。