Generic function in Kotlin
Level 4139 keystrokes
The type parameter <T> lets one function work with lists of any element type. At each call, T is inferred from the argument: Int for the first call and String for the second.
Kotlin code
// <T> before the name declares a type parameter used in List<T>1fun <T> printItems(items: List<T>) { // Each item has type T; println accepts any value2 for (item in items) {3 println(item)4 }5}6 // T is inferred as Int: prints 1, 2 and 3 on separate lines7printItems(listOf(1, 2, 3))// T is inferred as String: prints a, b and c8printItems(listOf("a", "b", "c"))Output
1 2 3 a b c
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.
(× 7)× 7"× 6,× 4{× 2}× 2<× 2>× 2:× 1