Kotlin Generic Classes
A generic class stores and returns values of a type chosen when an object is made. The class definition stays the same while each object works with its own chosen type.
A Box holds one typed value
Box stores one value of type T and show hands it back. One object fixes T as Int and the other fixes T as String.
class Box<T>(val value: T) {
fun show(): T {
return value
}
}
fun main() {
val numbers = Box(42)
val words = Box("kite")
println(numbers.show())
println(words.show())
}A generic data class
Entry is a data class with one type parameter. Printing the object shows the stored item and its count.
data class Entry<T>(val item: T, val count: Int)
fun main() {
val entry = Entry("pen", 3)
println(entry)
println(entry.item)
println(entry.count)
}Two type parameters
PairBox stores a key of type K and a value of type V. The describe method joins both stored values into one line of text.
class PairBox<K, V>(val key: K, val value: V) {
fun describe(): String {
return "$key - $value"
}
}
fun main() {
val pair = PairBox("id", 99)
println(pair.describe())
println(pair.key)
println(pair.value)
}Values go in and out with no cast
Holder stores one item behind get and set. The stored number comes back as an Int and can join a sum at once.
class Holder<T>(private var item: T) {
fun get(): T {
return item
}
fun set(newItem: T) {
item = newItem
}
}
fun main() {
val holder = Holder(10)
println(holder.get() + 5)
holder.set(25)
println(holder.get())
}Example
class Basket<T>(val items: List<T>) {
fun count(): Int {
return items.size
}
fun firstItem(): T {
return items[0]
}
}
fun main() {
val numbers = Basket(listOf(4, 8, 15))
val words = Basket(listOf("pen", "cup"))
println(numbers.count())
println(numbers.firstItem())
println(words.count())
println(words.firstItem())
}Key points
- A type parameter sits in angle brackets after the class name.
- Properties and methods use the type parameter as their type.
- Each object fixes the type parameter with its own type argument.
- A generic data class gains the standard data class behavior for its stored values.
- A class can hold two type parameters for two stored types.
- Typed values come back with their real type and need no cast.
In this example, Basket holds a list of type T items. The numbers basket holds three whole numbers and its first item is 4. The words basket holds two words and its first item is pen.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Kotlin Playground
Exercise
A program makes Box<String>("hi") from class Box<T>(val value: T). What is the type of value in that object?