验证 Kotlin 集合中的所有对象是否匹配,而不覆盖 equals

问题描述 投票:0回答:1

我正在开发一个 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
}
kotlin collections unique equality
1个回答
0
投票

创建一个将

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) }
© www.soinside.com 2019 - 2024. All rights reserved.