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 null1fun <T> List<T>.secondOrNull(): T? = if (size >= 2) this[1] else null2 // Upper bound: T must be Comparable<T>, which makes > available3fun <T : Comparable<T>> List<T>.isSorted(): Boolean { // Compare each pair of neighbors4 for (i in 0 until size - 1) { // A pair in the wrong order means the list is not sorted5 if (this[i] > this[i + 1]) return false6 } // No pair was out of order7 return true8}9 // Print 210println(listOf(1, 2, 3).secondOrNull())// Only one element: print null11println(listOf("a").secondOrNull())// Print true12println(listOf(1, 2, 3).isSorted())// 3 > 1, so print false13println(listOf(3, 1, 2).isSorted())Output
2 null true false
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