Generic Functions and Type Constraints with where
Write generic functions with single and multiple type constraints.
Generic Function Basics
Generic functions use type parameters in angle brackets before the function name. The type parameter can be used in parameter types and return types.
fun <T> identity(value: T): T = value
fun <T> listOf2(a: T, b: T): List<T> = listOf(a, b)
fun main() {
println(identity(42)) // 42
println(identity("hello")) // hello
println(listOf2(1, 2)) // [1, 2]
}Upper Bounds with : Constraint
Constrain a type parameter with an upper bound using :. The type must be a subtype of the bound.
fun <T : Comparable<T>> max(a: T, b: T): T = if (a >= b) a else b
fun main() {
println(max(3, 7)) // 7
println(max("apple", "banana")) // banana
// max(listOf(1), listOf(2)) // error: List is not Comparable
}All lessons in this course
- Generic Functions and Type Constraints with where
- Declaration-Site Variance: in and out
- Star Projection and When to Use *
- Type Erasure and reified Type Parameters