w3resource

Kotlin Sealed class and pattern matching: Handling operation results

Kotlin OOP Program: Exercise-3 with Solution

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.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/kotlin-exercises/oop/kotlin-oop-exercise-3.php