Kotlin Medium · Lesson 1 · On the house

Generics

Type params on classes/functions; constraints T : Comparable<T>. Lesson 1 is free — on the house.

Lessons · Kotlin Medium · Lesson 1 of 10 · On the house

Generics

Type params on classes/functions; constraints T : Comparable<T>.

Illustration for Kotlin
Lesson 1 is on the house.

A type parameter makes a declaration work for many types without casting. Write class Box<T>(val value: T) and fun <T> identity(x: T): T = x. The name T is a placeholder filled at each use site.

Call a generic function with inference when possible: identity(3) makes T be Int. Spell it when needed: identity<String>("hi"). Construct a generic class the same way: Box(42) or Box<Int>(42).

Constrain a parameter with an upper bound: fun <T : Comparable<T>> maxOf2(a: T, b: T): T = if (a >= b) a else b. Inside the body you may call members of Comparable on T. Without the bound, a >= b would not compile.

Multiple bounds use where: fun <T> sortCopy(list: List<T>): List<T> where T : Comparable<T>, T : Any. Default upper bound is Any?. Prefer one clear bound on the declaration when that is enough.

Misses: writing Java's T extends Comparable instead of T : Comparable<T>, assuming erased T survives as a runtime class without reification (next lessons), or using a raw type like Box without arguments when the API is generic.

generics

class Box<T>(val value: T)

fun <T> identity(x: T): T = x

fun <T : Comparable<T>> maxOf2(a: T, b: T): T =
    if (a >= b) a else b

fun main() {
    val b = Box(42)
    println(identity(b.value))
    println(maxOf2("ada", "grace"))
}
Match this when you type.

Quiz

How do you declare a generic class holding one value?

Quiz

What does T : Comparable<T> mean on a type parameter?

Quiz

How do you call a generic function with an explicit type arg?

Quiz

What is the default upper bound for an unconstrained T?

Check

Match the still for: Generics.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.