Part 13 / Topic 1 of 7
Generic classes and functions
A generic class or function takes a type parameter -- written in angle brackets, like
<T> -- so the same code works for String, Double, or any type you plug in later, without
copy-pasting it once per type.
class Crate<T>(private val items: MutableList<T> = mutableListOf()) {
val size: Int get() = items.size
fun add(item: T) { items.add(item) }
fun removeLast(): T? = if (items.isEmpty()) null else items.removeAt(items.size - 1)
fun peekAll(): List<T> = items.toList()
}
Crate<String> and Crate<Double> are two different, fully type-checked types at compile time --
riceCrate.add(199.0) simply does not compile, because riceCrate is a Crate<String>.
A generic function works the same way:
data class Page<T>(val items: List<T>, val pageNumber: Int, val totalPages: Int)
fun <T> paginate(all: List<T>, pageSize: Int, pageNumber: Int): Page<T> {
val chunks = all.chunked(pageSize)
val items = chunks.getOrElse(pageNumber - 1) { emptyList() }
return Page(items, pageNumber, chunks.size)
}
Real-world example: a Swadesh Mart warehouse system -- a Crate<T> holding one SKU's stock,
and paginate used for both a product-name listing and a price listing, from the exact same
function:
val riceCrate = Crate<String>()
riceCrate.add("Basmati 5kg")
riceCrate.add("Sona Masoori 10kg")
riceCrate.add("Idli Rice 1kg")
println("Crate has ${riceCrate.size} items: ${riceCrate.peekAll()}")
println("Removed: ${riceCrate.removeLast()}")
val productNames = listOf(
"Basmati Rice", "Toor Dal", "Sunflower Oil", "Atta 10kg", "Turmeric Powder",
"Red Chilli Powder", "Mustard Oil", "Jaggery", "Poha", "Besan"
)
val page2 = paginate(productNames, pageSize = 4, pageNumber = 2)
println("Page ${page2.pageNumber}/${page2.totalPages}: ${page2.items}")
Crate has 3 items: [Basmati 5kg, Sona Masoori 10kg, Idli Rice 1kg]
Removed: Idli Rice 1kg
Price crate: [199.0, 899.0]
Page 2/3: [Turmeric Powder, Red Chilli Powder, Mustard Oil, Jaggery]
Price page 1/2: [199.0, 899.0]
paginate was written once, against T, and ran correctly over a List<String> and a
List<Double> without any change -- that's the entire point of writing it generically instead
of once per type.
Full program: examples/01_generic_functions_and_classes.kt.
Done here? The practice set for Part 13 — including the solutions — is on the part page.