gpt4 book ai didi

if-statement - 多余的 'if'语句较少

转载 作者:行者123 更新时间:2023-12-02 13:01:42 24 4
gpt4 key购买 nike

我的代码如下

 private fun validateInput(): Boolean {
if (etReportRow1.text.toString() == ""
|| etReportRow2.text.toString() == ""
|| etReportRow3.text.toString() == "")
return false
else
return true
}

编译器告诉我

Redundant 'if' statement less... (Ctrl+F1) This inspection reports if statements which can be simplified to single statements. For example: if (foo()) { return true } else { return false } can be simplified to return foo().



建议的代码不会进入循环吗?

最佳答案

所有形式的陈述:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com