使用引用相等的 Kotlin Collection indexOf ===

jak*_*e n 3 collections kotlin

在 Kotlin 中,indexOf(x)调用 aCollection返回第一个元素的索引equals(x)(结构相等==

===如何才能获得基于引用相等 ( )的索引呢?

小智 6

解决这个问题的一种方法是使用indexOfFirst

data class Person(
    val firstName: String,
    val lastName: String,
    val age: Int
)

val targetPerson = Person("Greg", "Grimaldus", 47)

val people = listOf(
    Person("Tabitha", "Thimblewort", 38),

    Person("Shawn", "Been", 27),

    // not this one
    Person("Greg", "Grimaldus", 47),

    // this one
    targetPerson
)

people.indexOfFirst { it === targetPerson }
Run Code Online (Sandbox Code Playgroud)

可以对 any 执行相同的操作Collection,但请注意,如果Collection正在使用的是Set您想要的元素,则可能不存在,因为Sets 用于.equals()消除重复元素。