0
0
Kotlinprogramming~30 mins

Sealed classes for restricted hierarchies in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Sealed Classes for Restricted Hierarchies
📖 Scenario: Imagine you are building a simple app that handles different types of notifications: Email, SMS, and Push notifications. Each notification type has its own way of showing a message.
🎯 Goal: You will create a sealed class hierarchy to represent these notification types. Then, you will write code to handle each notification type safely and print the correct message.
📋 What You'll Learn
Create a sealed class called Notification.
Create three subclasses: Email, SMS, and Push inside Notification.
Add a message property to each subclass.
Write a function showNotification that takes a Notification and prints a message based on its type using when.
Call showNotification for each notification type.
💡 Why This Matters
🌍 Real World
Sealed classes help you model fixed sets of types, like different notification kinds, so your app can handle them safely and clearly.
💼 Career
Understanding sealed classes is important for Kotlin developers to write safe and maintainable code, especially when working with restricted hierarchies or state machines.
Progress0 / 4 steps
1
Create the sealed class and subclasses
Create a sealed class called Notification. Inside it, create three subclasses: Email, SMS, and Push. Each subclass should have a message property of type String.
Kotlin
Need a hint?

Use sealed class Notification and inside it define data class Email, SMS, and Push each with a message property.

2
Create a function to show notifications
Create a function called showNotification that takes a parameter notification of type Notification. Inside the function, use a when expression to check the type of notification and print the message with a prefix: "Email: ", "SMS: ", or "Push: ".
Kotlin
Need a hint?

Use when (notification) and check for each subclass with is Notification.Email, etc. Print the message with the correct prefix.

3
Create instances of each notification type
Create three variables: emailNotification, smsNotification, and pushNotification. Assign each one an instance of Notification.Email, Notification.SMS, and Notification.Push respectively, with messages: "Welcome to your inbox!", "You have a new text.", and "You have a new alert."
Kotlin
Need a hint?

Create variables with exact names and assign instances of each subclass with the given messages.

4
Print messages for all notifications
Call showNotification for each variable: emailNotification, smsNotification, and pushNotification. This will print the messages with their prefixes.
Kotlin
Need a hint?

Call showNotification with each notification variable to print their messages.