'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?
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lucas Burns |
