Kotlin Set indices
Syntax & Examples


Set.indices extension property

The indices extension property for sets in Kotlin returns an IntRange of the valid indices for the set. Note that since sets are unordered collections, the indices property is more conceptual and mainly used for consistent API design.


Syntax of Set.indices

The syntax of Set.indices extension property is:

val Set<*>.indices: IntRange

This indices extension property of Set returns an IntRange of the valid indices for this set.

Return Type

Set.indices returns value of type IntRange.



✐ Examples

1 Using indices to get the range of indices for a set

In Kotlin, we can use the indices extension property to get the range of valid indices for a set.

For example,

  1. Create a set of integers.
  2. Use the indices property to get the range of valid indices.
  3. Print the range of indices to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val numbers = setOf(1, 2, 3, 4, 5)
    val indices = numbers.indices
    println("The valid indices are: $indices")
}

Output

The valid indices are: 0..4

2 Using indices with a non-empty set

In Kotlin, we can use the indices property to get the valid indices of a non-empty set.

For example,

  1. Create a set of strings.
  2. Use the indices property to get the range of valid indices.
  3. Print the range of indices to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val fruits = setOf("apple", "banana", "cherry")
    val indices = fruits.indices
    println("The valid indices are: $indices")
}

Output

The valid indices are: 0..2

3 Using indices with an empty set

In Kotlin, we can use the indices property to get the valid indices of an empty set, which will result in an empty range.

For example,

  1. Create an empty set of integers.
  2. Use the indices property to get the range of valid indices.
  3. Print the range of indices to the console using the println function.

Kotlin Program

fun main(args: Array<String>) {
    val emptySet = emptySet<Int>()
    val indices = emptySet.indices
    println("The valid indices are: $indices")
}

Output

The valid indices are: 0..-1

Summary

In this Kotlin tutorial, we learned about indices extension property of Set: the syntax and few working examples with output and detailed explanation for each example.