CodeBlanks Logo Icon CodeBlanks

Generic class

Learn generic classes with class Box<T>.

Generic class

A generic class takes a type parameter. It is declared as class Box<T>; T stands for any type.

Example: class Box<T>(val value: T). This class is used as Box<Int>(5) or Box<String>("hello"). T is a type parameter; it is replaced by a concrete type at the call site. Generic classes boost reuse; you write the same logic for many types. Type safety is checked at compile time.

Using Box

When a generic class is called, the concrete type is given in angle brackets. T is replaced by that type.

Example: val intBox = Box<Int>(5); val strBox = Box<String>("hello"). intBox.value is an Int, strBox.value is a String. The type parameter is fixed at the call site; wrong types cause a compile error. This reduces runtime errors. Generic classes are common in collections, wrappers and stores.

Practice The Box<T> generic class

Define the generic class class Box<T>(val value: T). In main declare val intBox = Box<Int>(42) and print its value with println(intBox.value).

Starter code

Main.kt
// Define the Box<T> generic class
// with a value: T property
// instantiate with Int in main and print

Sample solution

Main.kt
class Box<T>(val value: T)

fun main() {
    val intBox = Box<Int>(42)
    println(intBox.value)
}

Expected output

42

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How is a <strong>generic class</strong> declared?

  • class Box(T)
  • class Box<T extends T>
  • class Box<T> Correct answer
  • class Box: T

Explanation: A generic class is written as class Box<T>.

2 Complete the generic Box definition

Question
class Box____(val value: T)
Answer
class Box<T>(val value: T)

Explanation: <T> is the type parameter in angle brackets.

3 Match the generic Box parts

Term Meaning
class Box<T> Class declaration
val value: T Type-parameterized property
Box<Int>(5) Concrete type call
intBox.value Access

All lessons in Intermediate