如何简化Kotlin中的谓词链

时间:2019-11-18 12:21:44

标签: kotlin boolean predicate chain

我有一系列谓词子句,像这样

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中是否有一种方法可以简化这种表达?

2 个答案:

答案 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
  1. 在对象run {}上调用范围函数student
  2. equals==取代以比较布尔值和null的值
  3. 范围函数的
  4. 返回类型可为空,因此使用?: false的elvis运算符。另一种选择是使用== true,但这是您的个人喜好