我的代码如下
private fun validateInput(): Boolean {
if (etReportRow1.text.toString() == ""
|| etReportRow2.text.toString() == ""
|| etReportRow3.text.toString() == "")
return false
else
return true
}
编译器告诉我
建议的代码不会进入循环吗?
最佳答案
所有形式的陈述:
if(condition){
return false
} else {
return true
}
可以简化为:
return !condition
因此,在您的情况下,它将导致:
return !(etReportRow1.text.toString() == "" || etReportRow2.text.toString() == "" || etReportRow3.text.toString() == "")
要么:
return
etReportRow1.text.toString().isNotEmpty() &&
etReportRow2.text.toString().isNotEmpty() &&
etReportRow3.text.toString().isNotEmpty()
注意:
isNotEmpty()
是扩展方法:public inline fun CharSequence.isNotEmpty(): Boolean = length > 0
为了避免重复的代码,您还可以使用
Sequence
:public fun validateInput() = sequenceOf(etReportRow1, etReportRow2, etReportRow3)
.map { it.text.toString() }
.all { it.isNotEmpty() }
关于if-statement - 多余的 'if'语句较少,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54143836/