Type Constraints with Upper Bounds in Kotlin
📖 Scenario: You are building a simple Kotlin program that works with shapes. Each shape can calculate its area. You want to write a function that accepts only shapes or their subclasses.
🎯 Goal: Create a generic function with a type constraint that accepts only objects of type Shape or its subclasses, and prints their area.
📋 What You'll Learn
Create an open class called
Shape with an abstract function area() that returns a Double.Create a subclass called
Circle that inherits from Shape and implements area().Create a generic function called
printArea with a type parameter T constrained to Shape or its subclasses.Inside
printArea, call the area() function of the passed object and print the result.💡 Why This Matters
🌍 Real World
Type constraints with upper bounds help ensure functions work only with compatible types, preventing errors and making code safer.
💼 Career
Understanding generics and type constraints is important for writing reusable and type-safe Kotlin code in professional Android or backend development.
Progress0 / 4 steps