Generic Functions
In this page:
Declaring a Generic Function
The type parameter goes in angle brackets right before the function name, letting the function's parameters and return type all refer to that same placeholder type.
Example: Declaring a Generic Function
fun <T> identity(value: T): T = value
fun main() {
println(identity(42))
println(identity("Kotlin"))
}
Login to try C/C++/Java/PHP code in the editor
Generic Functions on Collections
Generic functions are especially common for working with collections of any element type, such as returning the first two items regardless of what type they are.
Example: Generic Functions on Collections
fun <T> firstTwo(items: List<T>): List<T> = items.take(2)
fun main() {
println(firstTwo(listOf(1, 2, 3, 4)))
println(firstTwo(listOf("a", "b", "c")))
}
Login to try C/C++/Java/PHP code in the editor
Multiple Type Parameters in a Function
A generic function can declare more than one type parameter, useful for operations that combine two different kinds of values into a result.
Example: Multiple Type Parameters in a Function
fun <A, B> combine(a: A, b: B): String = "$a and $b"
fun main() {
println(combine(1, "one"))
println(combine(true, 3.14))
}
Login to try C/C++/Java/PHP code in the editor
Without a Constraint, T Is Treated as Any?
With no upper bound specified, T behaves like Any?, so the function can only do things valid for absolutely any type, like storing, returning, or comparing for equality.
Example: Without a Constraint, T Is Treated as Any?
fun <T> printTwice(value: T) {
println(value)
println(value)
}
fun main() {
printTwice(100)
printTwice("hello")
}
Login to try C/C++/Java/PHP code in the editor
- Placing the type parameter after the function name instead of before it; the correct order is
fun <T> functionName(...). - Assuming a generic function can perform type-specific operations (like arithmetic) on
Twithout any constraint restricting whatTcan be. - Redeclaring a type parameter already present on the enclosing class when it is not actually needed for that particular function.
- A generic function declares its type parameter before the function name:
fun <T> functionName(...). - The type parameter can appear in the parameter list, return type, or body of the function.
- Without constraints,
Tis treated asAny?, so only operations valid for any type (like storing or returning it) are allowed. - Generic functions let one implementation work correctly and safely across many different types.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: