Menu
Coddy logo textTech

Accessing Elements

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 68 of 93.

Now that you can create lists, you need to know how to retrieve individual elements from them. Kotlin uses index-based access, where each element has a position number starting from 0.

Use square brackets with the index to access an element:

val colors = listOf("Red", "Green", "Blue")
println(colors[0])  // Red
println(colors[1])  // Green
println(colors[2])  // Blue

You can also use the first() and last() functions for quick access to the endpoints:

val numbers = listOf(10, 20, 30, 40)
println(numbers.first())  // 10
println(numbers.last())   // 40

To find out how many elements a list contains, use the size property. Since indexing starts at 0, the last valid index is always size - 1:

val fruits = listOf("Apple", "Banana", "Cherry")
println(fruits.size)           // 3
println(fruits[fruits.size - 1])  // Cherry

Be careful not to access an index that doesn't exist - trying to access fruits[5] in a 3-element list will cause an error.

challenge icon

Challenge

Medium

Write a function getFirstAndLast that takes a list of integers and returns a string containing the first and last elements.

Use the appropriate list access methods to retrieve the first and last elements, then combine them into a formatted string.

Parameters:

  • numbers (List<Int>): A list of integers with at least one element

Returns: A string in the format "First: X, Last: Y" where X is the first element and Y is the last element.

Input constraints: The input list is nonempty.

Try it yourself

fun getFirstAndLast(numbers: List<Int>): String {
    // Write code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground