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