0
0
Kotlinprogramming~20 mins

Result type for functional error handling in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Result type for functional error handling
📖 Scenario: Imagine you are building a simple calculator app that divides two numbers. Sometimes, the user might enter zero as the divisor, which causes an error. We want to handle this error in a clean way using Kotlin's Result type.
🎯 Goal: You will create a function that divides two numbers and returns a Result type to handle success or failure. Then, you will use this function and print the result or error message.
📋 What You'll Learn
Create a function called safeDivide that takes two Int parameters: numerator and denominator.
Inside safeDivide, return Result.success with the division result if the denominator is not zero.
If the denominator is zero, return Result.failure with an IllegalArgumentException and message "Cannot divide by zero".
Call safeDivide with numerator 10 and denominator 0, and store the result in a variable called result.
Use result.fold to print "Result: <value>" if successful, or "Error: <message>" if failure.
💡 Why This Matters
🌍 Real World
Handling errors without crashing apps is important in real-world software. Using <code>Result</code> helps manage errors clearly and safely.
💼 Career
Many Kotlin projects use <code>Result</code> or similar types for error handling. Knowing this helps you write robust code and work well in teams.
Progress0 / 4 steps
1
Create the safeDivide function
Write a function called safeDivide that takes two Int parameters named numerator and denominator. The function should return a Result<Int>.
Kotlin
Need a hint?

Use the fun keyword to define the function with two Int parameters and return type Result<Int>.

2
Return success or failure inside safeDivide
Inside the safeDivide function, write an if statement to check if denominator is zero. If it is zero, return Result.failure(IllegalArgumentException("Cannot divide by zero")). Otherwise, return Result.success(numerator / denominator).
Kotlin
Need a hint?

Use if (denominator == 0) to check for zero and return failure or success accordingly.

3
Call safeDivide and store the result
Call the safeDivide function with numerator 10 and denominator 0. Store the returned Result in a variable called result.
Kotlin
Need a hint?

Use val result = safeDivide(10, 0) to call the function and save the result.

4
Print the result or error message using fold
Use result.fold to print the success value with "Result: <value>" or print the error message with "Error: <message>". Use println inside the lambdas.
Kotlin
Need a hint?

Use result.fold(onSuccess = { ... }, onFailure = { ... }) to handle both cases and print messages.