0
0
Kotlinprogramming~30 mins

Type constraints with upper bounds in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create the Shape class
Create an open class called Shape with an abstract function area() that returns a Double.
Kotlin
Need a hint?

Use open abstract class Shape and define abstract fun area(): Double inside it.

2
Create the Circle subclass
Create a class called Circle that inherits from Shape. Add a property radius of type Double and override the area() function to return the area of the circle using 3.14 * radius * radius.
Kotlin
Need a hint?

Use class Circle(val radius: Double) : Shape() and override area().

3
Create the generic function with upper bound
Create a generic function called printArea with a type parameter T that has an upper bound of Shape. The function should take a parameter shape of type T and print the area by calling shape.area().
Kotlin
Need a hint?

Define fun <T : Shape> printArea(shape: T) and print the area.

4
Call the function and print the area
Create a Circle object with radius 5.0 and call printArea with this object. Print the output.
Kotlin
Need a hint?

Create val circle = Circle(5.0) and call printArea(circle).