0
0
Kotlinprogramming~20 mins

Sealed classes with when exhaustive check in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Sealed classes with when exhaustive check
📖 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 data.
🎯 Goal: You will create sealed classes to represent these notification types and use a when expression to handle each type with an exhaustive check.
📋 What You'll Learn
Create a sealed class called Notification with three subclasses: Email, SMS, and Push
Add properties to each subclass as specified
Create a variable called notification with a specific subclass instance
Use a when expression with exhaustive check to handle all notification types
Print a message describing the notification
💡 Why This Matters
🌍 Real World
Sealed classes help represent fixed sets of related types, like different notification types in an app, making code safer and easier to maintain.
💼 Career
Understanding sealed classes and exhaustive <code>when</code> expressions is important for Kotlin developers building robust and clear applications.
Progress0 / 4 steps
1
Create sealed class and subclasses
Create a sealed class called Notification with three subclasses: Email with a subject property of type String, SMS with a phoneNumber property of type String, and Push with 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 inheriting from Notification.

2
Create a notification instance
Create a variable called notification and assign it an instance of Notification.Email with the subject set to "Welcome to Kotlin".
Kotlin
Need a hint?

Use val notification: Notification = Notification.Email("Welcome to Kotlin") to create the instance.

3
Use when expression with exhaustive check
Write a when expression using the variable notification to handle all subclasses: Email, SMS, and Push. For each case, create a string message describing the notification. Assign the result to a variable called message. Make sure the when expression is exhaustive.
Kotlin
Need a hint?

Use val message = when (notification) { ... } with all subclasses handled.

4
Print the message
Write a println statement to display the value of the variable message.
Kotlin
Need a hint?

Use println(message) to display the message.