rwallace
rwallace

Reputation: 33395

Why is indices a property of collection rather than list?

Kotlin lists have the useful property indices that provides the range of valid indices.

But according to https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/indices.html it is actually a property not just of lists but of collections. Tried an experiment and sure enough, a set also has this property.

But sets cannot be indexed by integer the way lists can. So it's not meaningful to talk about the indices of a set.

Given that, why is it a property of collections in general rather than just lists (and arrays)?

Upvotes: 2

Views: 109

Answers (1)

hanh
hanh

Reputation: 406

But sets cannot be indexed by integer the way lists can. So it's not meaningful to talk about the indices of a set.

Having the ability the randomly access an element by index is one of the usages of indices. But you could be using them as integer keys. Basically they are defined as a integer range mapping to elements, so this works for any collection. In code, it is simply implemented as [0..size)

Upvotes: 1

Related Questions