我试图通过使用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
}它可以工作,但我认为它可以改进。
发布于 2019-01-15 10:40:57
它可以简化如下:
infix fun String?.orIfNullOrEmpty(other: String?) =
takeUnless { it.isNullOrBlank() } ?: other您可以使用this (在本例中,可以在this上直接调用takeUnless { },因为扩展),如果它不是空或空,则为other。
注意,Kotlin已经有了isNullOrBlank和类似的扩展。
https://stackoverflow.com/questions/54197040
复制相似问题