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
- Generic Functions and Classes
- Declaration-Site Variance
- Use-Site Variance
- Generic Constraints