0
0
Kotlinprogramming~3 mins

Why Type constraints with upper bounds in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your functions could automatically know which types they can work with, without you writing extra checks?

The Scenario

Imagine you want to write a function that works only with certain types, like numbers or shapes, but you have to check each type manually every time you use it.

The Problem

This manual checking makes your code long, confusing, and easy to break. You might forget a type or write repeated code for each case, which wastes time and causes bugs.

The Solution

Type constraints with upper bounds let you tell the computer exactly which types are allowed, so your function automatically works only with those types. This keeps your code clean, safe, and easy to reuse.

Before vs After
Before
fun printArea(shape: Any) {
  if (shape is Circle) println(shape.radius * shape.radius * 3.14)
  else if (shape is Square) println(shape.side * shape.side)
}
After
fun <T : Shape> printArea(shape: T) {
  println(shape.area())
}
What It Enables

You can write flexible, reusable functions that work safely with a group of related types without extra checks.

Real Life Example

Suppose you build a drawing app that handles different shapes. Using type constraints, you can create one function to calculate areas for all shapes that share a common interface.

Key Takeaways

Manual type checks make code long and error-prone.

Upper bounds let you restrict types clearly and safely.

This leads to cleaner, reusable, and safer code.