0
0
Kotlinprogramming~5 mins

Generic function declaration in Kotlin

Choose your learning style9 modes available
Introduction
Generic functions let you write one function that works with many types, so you don't repeat code for each type.
When you want a function to work with different types like Int, String, or custom classes.
When you want to create reusable code that handles many data types safely.
When you want to avoid writing multiple versions of the same function for different types.
Syntax
Kotlin
fun <T> functionName(param: T): T {
    // function body
    return param
}
The before the function name declares a generic type T.
You can use any letter or name instead of T, but T is common for 'Type'.
Examples
A simple generic function that returns whatever you give it.
Kotlin
fun <T> echo(item: T): T {
    return item
}
A generic function that prints any type of item.
Kotlin
fun <T> printItem(item: T) {
    println(item)
}
A generic function that returns the first item from a list or null if empty.
Kotlin
fun <T> firstItem(list: List<T>): T? {
    return list.firstOrNull()
}
Sample Program
This program shows the generic function echo working with Int, String, and Double types.
Kotlin
fun <T> echo(item: T): T {
    return item
}

fun main() {
    println(echo(123))
    println(echo("Hello"))
    println(echo(3.14))
}
OutputSuccess
Important Notes
Generic functions help keep your code clean and avoid duplication.
You can use multiple generic types like if needed.
Kotlin checks types at compile time to keep your code safe.
Summary
Generic functions let you write one function for many types.
Declare generic types with <T> before the function name.
Use generic functions to make your code reusable and safe.