Generic functions
- Kotlin course
- Intermediate
- Lesson 48/116
- 5 min
Learn generic functions with fun <T>.
Generic function
A generic function takes a type parameter. It is declared as fun <T> ident(t: T): T; the type parameter is written before the function name.
Example: fun <T> ident(t: T): T { return t }. This function is called as ident<Int>(5) or ident("hello"). In the second call Kotlin infers the type; T becomes String. Generic functions let you write type-safe helpers. The type parameter is written BEFORE the function name; this is an important detail.
Type inference
When a generic function is called, the type parameter is usually inferred. Writing it explicitly is optional.
Example: fun <T> singleton(value: T): List<T> { return listOf(value) }. In singleton(5) Kotlin infers T as Int; the result is List<Int>. You can also write singleton<String>("hello") explicitly. Type inference keeps code short; you can still write the explicit type when it helps readability. The compiler checks type safety in both cases.
Practice The ident generic function
Define the generic function fun <T> ident(t: T): T whose body returns t. In main call println(ident(42)) and println(ident("hello")) on separate lines.
Starter code
// Define the ident generic function
// takes t: T, returns T
// call with Int and String in main and printSample solution
fun <T> ident(t: T): T {
return t
}
fun main() {
println(ident(42))
println(ident("hello"))
}Expected output
42 hello
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the generic function parts
| Term | Meaning |
|---|---|
fun <T> ident |
Type-parameterized signature |
(t: T) |
Type-parameterized parameter |
: T |
Return type |
ident<Int>(5) |
Call |
2 Where is the type parameter written in a <strong>generic function</strong> declaration?
- After the return type
- After the function name
- At the end of the parameter list
- Before the function name, with fun Correct answer
Explanation: The type parameter is written before the name, as in fun <T> ident.
3 Complete the generic function definition
fun ____ ident(t: T): T {
return t
}
fun <T> ident(t: T): T {
return t
}
Explanation: fun <T> ident(t: T) is a generic function declaration.