Introduction
Generic functions let you write one function that works with many types, so you don't repeat code for each type.
fun <T> functionName(param: T): T { // function body return param }
fun <T> echo(item: T): T { return item }
fun <T> printItem(item: T) { println(item) }
fun <T> firstItem(list: List<T>): T? { return list.firstOrNull() }
fun <T> echo(item: T): T { return item } fun main() { println(echo(123)) println(echo("Hello")) println(echo(3.14)) }
<T> before the function name?<T> before a function name means the function can accept any type as input.printItem that takes a parameter of any type T in Kotlin?<T>.T, so item: T is correct.fun <T> identity(value: T): T {
return value
}
fun main() {
println(identity(123))
println(identity("Hello"))
}identity returns the same value it receives, regardless of type.identity(123) returns 123, and identity("Hello") returns "Hello".fun printValue<T>(value: T) {
println(value)
}printValue<T>, which is incorrect syntax.swap that swaps two elements in a mutable list at given indices. Which of the following is the correct Kotlin function declaration and implementation?<T> must be declared before the function name. The list must be mutable to allow swapping.i and j using a temporary variable, which is correct.Pass the test and this pattern moves unknown