Reputation: 485
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
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 Set
s use .equals()
to eliminate duplicate elements.
Upvotes: 6