改进中缀 isNullOrEmpty
Improve infix isNullOrEmpty
我正在尝试使用中缀改进一些代码:
工作代码(但有点难看...):
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
}
它有效,但我认为它可以改进
可以这样简化:
infix fun String?.orIfNullOrEmpty(other: String?) =
takeUnless { it.isNullOrBlank() } ?: other
如果它不为 null 或空白,则采用 this
(在这种情况下,takeUnless { }
可以直接在 this
上调用,因为扩展名),否则采用 other
。
请注意,Kotlin 已经有 isNullOrBlank
和类似的扩展。
我正在尝试使用中缀改进一些代码:
工作代码(但有点难看...):
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
}
它有效,但我认为它可以改进
可以这样简化:
infix fun String?.orIfNullOrEmpty(other: String?) =
takeUnless { it.isNullOrBlank() } ?: other
如果它不为 null 或空白,则采用 this
(在这种情况下,takeUnless { }
可以直接在 this
上调用,因为扩展名),否则采用 other
。
请注意,Kotlin 已经有 isNullOrBlank
和类似的扩展。