0Pricing
Kotlin Academy · Lesson

Generic Functions and Classes

Parameterize types.

What Are Generics?

Generics let you write code that works with many types while keeping full type safety. Instead of fixing a concrete type, you use a type parameter (often T) as a placeholder.

A Generic Function

A generic function declares its type parameter in angle brackets before the function name. Here T can be any type.

fun <T> identity(value: T): T {
    return value
}

fun main() {
    println(identity(42))
    println(identity("hello"))
}

All lessons in this course

  1. Generic Functions and Classes
  2. Declaration-Site Variance
  3. Use-Site Variance
  4. Generic Constraints
← Back to Kotlin Academy