我有一系列谓词子句,像这样
student?.firstName?.equals("John") ?: false &&
student?.lastName?.equals("Smith") ?: false &&
student?.age?.equals(20) ?: false &&
student?.homeAddress?.equals("45 Boot Terrace") ?: false &&
student?.cellPhone?.startsWith("123456") ?: false
我发现,可以代替 && 来使用布尔谓词 and(),但是总的来说,这并不能使代码更加简洁。
Kotlin中是否有一种方法可以简化这种表达?
答案 0 :(得分:0)
例如
val result = listOf(
student.firstName == "John",
student.lastName == "Smith",
student.age == 20,
student.cellPhone.orEmpty().startsWith("123456")
).all { it }
或
fun isAllTrue(first: Boolean, vararg other: Boolean): Boolean {
return first && other.all { it }
}
val result = isAllTrue(
student.firstName == "John",
student.lastName == "Smith",
student.age == 20,
student.cellPhone.orEmpty().startsWith("123456")
)
或
fun Iterable<Boolean>.isAllTrue(): Boolean {
return all { it }
}
val result = listOf(
student.firstName == "John",
student.lastName == "Smith",
student.age == 20,
student.cellPhone.orEmpty().startsWith("123456")
).isAllTrue()
答案 1 :(得分:0)
感谢大家参加!这是带注释的代码的最终版本:
student?.run {
firstName == "John" &&
lastName == "Smith" &&
age == 20 &&
homeAddress == "45 Boot Terrace" &&
cellPhone.orEmpty().startsWith("123456")
} ?: false
run {}
上调用范围函数student
equals
被==
取代以比较布尔值和null
的值?: false
的elvis运算符。另一种选择是使用== true
,但这是您的个人喜好