我正在开发一个 kotlin 函数,该函数需要验证集合中的所有对象对于特定属性是否具有相同的值。通常我会简单地使用distinctBy()并检查结果列表的大小是否为<= 1. However, this particular function has an added complication. Two of the possible values need to be treated as 'matching' even though they have different values for the field being compared. I don't want to override the 'equals' method since the logic only applies in this particular function. I could also brute force the problem and simply do a manual comparison of every object in the list against every other item but that doesn't seem very efficient. What other options do I have?
作为参考,我的数据模型如下所示:
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
映射到相同数字的函数:
fun customMapping(v: IdocsDocumentOwner) = when(v) {
Parent1, Parent2 -> -1 // make sure no other idocsCode is this number
else -> v.idocsCode
}
然后像这样使用它:
val distinctOwners = owners.distinctBy { customMapping(it) }