Kotlin Sealed class and pattern matching: Handling operation results
Write a Kotlin object-oriented program that creates a sealed class Result with subclasses Success and Error to represent the result of an operation. Use pattern matching to handle different result types.
Pre-Knowledge (Before You Start!)
Before attempting this exercise, you should be familiar with the following concepts:
- Sealed Classes: Understanding how sealed classes restrict inheritance to a fixed set of subclasses.
- Data Classes: Using data classes to store structured data with built-in functionality like toString(), equals(), and hashCode().
- When Expression: Using Kotlin’s when expression for pattern matching to handle different cases.
- Encapsulation: Encapsulating success and error states within a single type hierarchy.
Hints (Try Before Looking at the Solution!)
Try to solve the problem using these hints:
- Hint 1: Define a sealed class Result and two subclasses: Success and Error.
- Hint 2: The Success class should contain a property for successful operation data.
- Hint 3: The Error class should contain a property for an error message.
- Hint 4: Use a when expression to check if the result is Success or Error.
- Hint 5: In the main() function, create instances of Success and Error and process them.
Sample Solution:
Kotlin Code:
sealed class Result {
data class Success(val data: String) : Result()
data class Error(val errorMessage: String) : Result()
}
fun processResult(result: Result) {
when (result) {
is Result.Success -> {
println("Operation succeeded. Data: ${result.data}")
}
is Result.Error -> {
println("Operation failed. Error message: ${result.errorMessage}")
}
}
}
fun main() {
val successResult = Result.Success("Data loaded successfully")
val errorResult = Result.Error("Failed to load data")
processResult(successResult)
processResult(errorResult)
}
Sample Output:
Operation succeeded. Data: Data loaded successfully Operation failed. Error message: Failed to load data
Explanation:
In the above exercise -
- First, we have a sealed class "Result" with two subclasses Success and Error. The sealed class restricts the possible subclasses to only those defined within the same file.
- The "Success" class holds the data of a successful operation, and the Error class holds the error message in case of a failed operation.
- The "processResult()" function takes a parameter of type Result and uses pattern matching (the when expression) to handle different result types. If the result is of type Result.Success, it extracts the data and prints a success message. If the result is of type Result.Error, it extracts the error message and prints an error message.
- In the "main()" function, we create instances of Result.Success and Result.Error, and pass them to the processResult() function to handle the different result types using pattern matching.
Kotlin Editor:
Previous: Implementing a logger for logging functionality.
Next: Modifying component behavior.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics