我正在开发一个 kotlin 函数,该函数需要验证集合中的所有对象对于特定属性是否具有相同的值。通常,我只需使用 distinctBy() 并检查结果列表的大小是否 <= 1。但是,这个特定的函数增加了复杂性。两个可能的值需要被视为“匹配”,即使它们对于被比较的字段具有不同的值。我不想覆盖“equals”方法,因为该逻辑仅适用于这个特定的函数。我也可以强行解决问题,只需手动将列表中的每个对象与其他每个项目进行比较,但这似乎效率不高。我还有什么其他选择?
作为参考,我的数据模型如下:
internal enum class IdocsDocumentOwner(val idocsCode: Int, val ownerType: String) {
Student(2, "Student"),
Spouse(3, "Student Spouse"),
Parent1(5, "Father"),
Parent2(6, "Mother"),
NonCustodialParent(7, "Noncustodial"),
Other(8, "Other");
}
然后我有一个验证函数,例如:
fun validateIdocsGroupFiles( owners:List<IdocsDocumentOwner> ){
val distinctOwners = owners.distinctBy { it.owner.idocsCode }
assert(distinctOwners.count() <= 1)
//[Student,Student] == true
//[Student,Parent1] == false
//[Parent1,Parent2] == true
}
Parent1
创建一个将和映射Parent2
到相同数字的函数:然后像这样使用它: