Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 13 / Topic 2 of 7

Bounded type parameters and where clauses

An unbounded <T> can be anything, which also means you can't do much with it -- no <, no .length, nothing beyond what every single type supports (toString(), ==). An upper bound (T : Comparable<T>) narrows T down to types that support a specific operation, in exchange for being allowed to use that operation inside the function.

fun <T : Comparable<T>> costliestOf(a: T, b: T, c: T): T {
    val higher = if (a > b) a else b
    return if (higher > c) higher else c
}

a > b only compiles because the bound guarantees T has a compareTo. Call costliestOf with anything that implements Comparable -- Double, String, your own class -- and it works; call it with something that doesn't, and it's a compile error, not a runtime surprise.

When one type parameter needs more than one bound, T : X in the angle brackets only allows one -- a where clause lists them all:

interface Priced {
    val priceInRupees: Double
}

data class Product(val name: String, override val priceInRupees: Double) : Priced

data class Discounted(val product: Product, val discountPercent: Double) : Priced, Comparable<Discounted> {
    override val priceInRupees: Double get() = product.priceInRupees * (1 - discountPercent / 100)
    override fun compareTo(other: Discounted): Int = priceInRupees.compareTo(other.priceInRupees)
}

fun <T> cheapestAfterDiscount(items: List<T>): T where T : Priced, T : Comparable<T> =
    items.minOrNull() ?: throw NoSuchElementException("items must not be empty")
println("Costliest of three prices: ${costliestOf(199.0, 899.0, 45.0)}")
println("Costliest of three names: ${costliestOf("Rice", "Dal", "Sugar")}")

val items = listOf(
    Discounted(Product("Basmati Rice", 420.0), discountPercent = 10.0),
    Discounted(Product("Toor Dal", 180.0), discountPercent = 0.0),
    Discounted(Product("Sunflower Oil", 210.0), discountPercent = 15.0),
)
val cheapest = cheapestAfterDiscount(items)
println("Cheapest after discount: ${cheapest.product.name} at ₹${"%.2f".format(cheapest.priceInRupees)}")
Costliest of three prices: 899.0
Costliest of three names: Sugar
Cheapest after discount: Sunflower Oil at ₹178.50

"Sugar" wins the second line for the same reason it would in a dictionary: 'R' < 'S', so "Rice" > "Sugar" is false, and the comparison falls through to "Sugar". Sunflower Oil wins the discount comparison because 15% off ₹210 (₹178.50) beats 10% off ₹420 (₹378) and 0% off ₹180.

Full program: examples/02_bounded_type_parameters_and_where.kt.

Done here? The practice set for Part 13 — including the solutions — is on the part page.

Search the guide