Store a value while keeping its type.

generic-class A generic class can keep the type of the value it stores.

Generic Box

item
GenericBox.kt
Replay: real traced execution (multi-file project)
class Box<T>(val value: T) {
    fun label(): String {
        return "value:$value"
    }
}

fun main() {
    val item = "tea"
    val box = Box(item)
    val label = box.label()

    println("item=$item")
    println("label=$label")
}
class Box<T>(val value: T) {
    fun label(): String {
        return "value:$value"
    }
}

fun main() {
    val item = "jam"
    val box = Box(item)
    val label = box.label()

    println("item=$item")
    println("label=$label")
}
class Box<T>(val value: T) {
    fun label(): String {
        return "value:$value"
    }
}

fun main() {
    val item = "map"
    val box = Box(item)
    val label = box.label()

    println("item=$item")
    println("label=$label")
}
  1. item ← tea

    7fun main() {8    val item→ tea = "tea" //@item="jam", "map"9    val box = Box(itemtea)10    val label = box.label()
  2. fun label(): String

    1class Box<T>(val value: T) {2    fun label(): String {3        return "value:$valuetea"4    }
  3. label ← value:tea

    9    val box = Box(item)10    val label→ value:tea = box.label()1112    println("item=$itemtea")13    println("label=$labelvalue:tea")14}
    outputitem=tea
    label=value:tea
  1. item ← jam

    7fun main() {8    val item→ jam = "jam"9    val box = Box(itemjam)10    val label = box.label()
  2. fun label(): String

    1class Box<T>(val value: T) {2    fun label(): String {3        return "value:$valuejam"4    }
  3. label ← value:jam

    9    val box = Box(item)10    val label→ value:jam = box.label()1112    println("item=$itemjam")13    println("label=$labelvalue:jam")14}
    outputitem=jam
    label=value:jam
  1. item ← map

    7fun main() {8    val item→ map = "map"9    val box = Box(itemmap)10    val label = box.label()
  2. fun label(): String

    1class Box<T>(val value: T) {2    fun label(): String {3        return "value:$valuemap"4    }
  3. label ← value:map

    9    val box = Box(item)10    val label→ value:map = box.label()1112    println("item=$itemmap")13    println("label=$labelvalue:map")14}
    outputitem=map
    label=value:map