0
0
KotlinHow-ToBeginner · 3 min read

How to Create Generic Function in Kotlin: Simple Guide

In Kotlin, you create a generic function by adding a type parameter inside angle brackets <T> before the function name. This allows the function to work with any type, making your code reusable and type-safe.
📐

Syntax

A generic function in Kotlin uses a type parameter declared in angle brackets <T> before the function name. The type parameter T can be used as a placeholder for any type inside the function.

  • <T>: Declares a generic type parameter named T.
  • fun: Keyword to declare a function.
  • functionName: Your function's name.
  • param: T: Parameter of generic type T.
  • return type: Can also use T or other types.
kotlin
fun <T> genericFunction(param: T): T {
    return param
}
💻

Example

This example shows a generic function that returns the same value it receives, demonstrating how the generic type T works with different data types.

kotlin
fun <T> echo(value: T): T {
    return value
}

fun main() {
    println(echo(123))        // Works with Int
    println(echo("Hello"))  // Works with String
    println(echo(3.14))       // Works with Double
}
Output
123 Hello 3.14
⚠️

Common Pitfalls

Common mistakes include forgetting to declare the generic type parameter <T> before the function name or trying to use a generic type without specifying it properly. Also, generic functions cannot use primitive types directly without boxing.

Wrong example (missing <T>):

kotlin
fun wrongFunction(param: T): T { // Error: T is not declared
    return param
}

// Correct way:
fun <T> correctFunction(param: T): T {
    return param
}
📊

Quick Reference

ConceptDescription
Declares a generic type parameter
fun functionName(param: T): TGeneric function syntax
TGeneric type placeholder used in parameters and return type
Type SafetyEnsures function works with any type safely
BoxingPrimitive types are boxed when used as generic types

Key Takeaways

Declare generic type parameters with before the function name.
Use the generic type T as a placeholder for parameters and return types.
Generic functions increase code reuse and type safety.
Always declare the generic type parameter to avoid compilation errors.
Primitive types are automatically boxed when used with generics.