First and last list elements in Kotlin

Level 3113 keystrokes

first() and last() return the first and last elements. firstOrNull { } returns the first element that matches the condition, or null when none does, instead of throwing like first { } would.

Kotlin code

// A list of the numbers 1 to 5
1val nums = listOf(1, 2, 3, 4, 5)
// first() returns the first element: prints 1 (it throws on an empty list)
2println(nums.first())
// last() returns the last element: prints 5
3println(nums.last())
// No element is greater than 10, so firstOrNull returns null and null is printed
4println(nums.firstOrNull { it > 10 })

Output

1
5
null
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Kotlin code and how often they appear.

  • (× 6
  • )× 6
  • ,× 4
  • .× 3
  • {× 1
  • }× 1
  • =× 1
  • >× 1

More Kotlin examples at level 3

← Kotlin typing practice