Generic extension functions in Kotlin

Level 5359 keystrokes

Generic extension functions add methods to List<T> for any element type. secondOrNull() returns the second element or null, and isSorted() uses the upper bound T : Comparable<T> so that elements can be compared with >.

Kotlin code

// Extension on List<T>: index 1 if there are at least 2 elements, otherwise null
1fun <T> List<T>.secondOrNull(): T? = if (size >= 2) this[1] else null
2
// Upper bound: T must be Comparable<T>, which makes > available
3fun <T : Comparable<T>> List<T>.isSorted(): Boolean {
// Compare each pair of neighbors
4 for (i in 0 until size - 1) {
// A pair in the wrong order means the list is not sorted
5 if (this[i] > this[i + 1]) return false
6 }
// No pair was out of order
7 return true
8}
9
// Print 2
10println(listOf(1, 2, 3).secondOrNull())
// Only one element: print null
11println(listOf("a").secondOrNull())
// Print true
12println(listOf(1, 2, 3).isSorted())
// 3 > 1, so print false
13println(listOf(3, 1, 2).isSorted())

Output

2
null
true
false
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.

  • (× 17
  • )× 17
  • >× 7
  • ,× 6
  • .× 6
  • <× 5
  • :× 3
  • [× 3
  • ]× 3
  • "× 2

More Kotlin examples at level 5

← Kotlin typing practice