如何简化Kotlin中的谓词链

问题描述 投票:2回答:2

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

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

kotlin boolean predicate chain
2个回答
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()

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. 作用域函数的返回类型为空,因此使用elvis运算符?: false。另一种选择是使用== true,但这是您的个人喜好
© www.soinside.com 2019 - 2024. All rights reserved.