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 51val 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 53println(nums.last())// No element is greater than 10, so firstOrNull returns null and null is printed4println(nums.firstOrNull { it > 10 })Output
1 5 null
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