Search

Dark theme | Light theme

December 9, 2022

Kotlin Kandy: Getting The Indices Of A Collection

Kotlin adds a lot of useful extensions to the collection classes. One of them is the indices property. The indices property returns the indices of the elements in the collection as an IntRange.

// With the indices property we get back the
// index values for each element, starting with 0
// as an IntRange.
val list = listOf(3, 20, 10, 2, 1)
assert(list.indices == 0..4)


// Helper function to return the position in the alphabet
// of a given letter.
fun findLetterIndex(c: Char): Int {
    // Range of all letters.
    val alphabet = 'a'..'z'

    // Combine letters in alphabet with their position (zero-based).
    // Result: [(a, 0), (b, 1), (c, 2), ...]
    val alphabetIndices = alphabet.zip(alphabet.toList().indices)

    // Find position, if not found return -1.
    val position = alphabetIndices.find { p -> p.first == c}?.second ?: -1

    // Fix the zero based index values.
    return position + 1
}

val positionInAlphabet = "kotlin".map(::findLetterIndex)
assert(positionInAlphabet == listOf(11, 15, 20, 12, 9, 14))

Written with Kotlin 1.7.20.