konrad_sx
konrad_sx

Reputation: 485

Kotlin Collection indexOf using reference equality ===

In Kotlin, indexOf(x) called on a Collection returns the index of the first element that equals(x) (structural equality ==)

How can one get the index based on referential equality (===) instead?

Upvotes: 3

Views: 389

Answers (1)

Lucas Burns
Lucas Burns

Reputation: 409

One solution to this would be to use 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 }

The same can be done with any Collection, but be aware if the Collection in use is a Set your desired element may not be present since Sets use .equals() to eliminate duplicate elements.

Upvotes: 6

Related Questions