AnyCompiler

Generics

Box<T> is a generic class — T is a placeholder filled in with a real type wherever Box is used. Box("hello") infers Box<String> automatically from the argument, with the compiler checking type safety at every use.

class Box<T>(private val contents: T) {
    fun getValue(): T = contents
}

fun main() {
    val box = Box("hello")
    println(box.getValue())
}
Output
hello

Next: exceptions, and a closing look at what this course covered.

Practice exercise

Define a generic class Box<T> with a private contents property and a getValue() method. Create a Box holding "hello", then print its value.