Bird
Raised Fist0
Kotlinprogramming~10 mins

Result type for functional error handling in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Result type for functional error handling
Start Function
↓
Try Operation
↓
Success?
Yes→Return Success Result
↓
End Function
↓
No
→Return Failure Result
↓
End Function
The function tries an operation, then returns a success or failure wrapped in a Result type.
Execution Sample
Kotlin
fun divide(a: Int, b: Int): Result<Int> {
    return if (b != 0) {
        Result.success(a / b)
    } else {
        Result.failure(ArithmeticException("Division by zero"))
    }
}
This function divides two numbers and returns a Result with success or failure.
Execution Table
StepConditionResult CreatedReturned ValueExplanation
1b != 0 (b=2)SuccessResult.success(2)Since b is 2, division proceeds successfully.
2b != 0 (b=0)FailureResult.failure(ArithmeticException)Since b is 0, failure result is returned.
💡 Function returns Result.success or Result.failure based on condition b != 0.
Variable Tracker
VariableStartAfter Step 1After Step 2
a555
b2 or 020
ResultnullSuccess(2)Failure(ArithmeticException)
Key Moments - 2 Insights
Why do we use Result.success and Result.failure instead of throwing exceptions?
Using Result wraps success or failure as values, so the caller can handle errors without try-catch blocks, as shown in execution_table rows 1 and 2.
What happens if b is zero in the divide function?
The condition b != 0 is false, so Result.failure with an exception is returned, as seen in execution_table row 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the returned value when b = 2?
AResult.failure(ArithmeticException)
Bnull
CResult.success(2)
DThrows exception
💡 Hint
Check execution_table row 1 for b=2 condition and returned value.
At which step does the function return a failure Result?
AStep 1
BStep 2
CNever
DBoth steps
💡 Hint
Look at execution_table row 2 where b=0 and failure is returned.
If we change the function to throw exceptions instead of returning Result, how would the execution_table change?
AIt would show thrown exceptions instead of Result values
BIt would remain the same
CIt would show success only
DIt would show failure only
💡 Hint
Think about how exceptions differ from returning Result as shown in the execution_table.
Concept Snapshot
Result type wraps success or failure values.
Use Result.success(value) for success.
Use Result.failure(exception) for errors.
Caller handles Result without try-catch.
Avoids throwing exceptions directly.
Simplifies error handling in functional style.
Full Transcript
This Kotlin function divides two integers and returns a Result type to handle errors functionally. It checks if the divisor b is not zero. If true, it returns Result.success with the division result. Otherwise, it returns Result.failure with an ArithmeticException. This approach wraps success and failure as values, letting callers handle errors without exceptions. The execution table shows two steps: one for success when b=2, and one for failure when b=0. Variables a and b remain constant, while Result changes based on the condition. Key moments clarify why Result is used instead of exceptions and what happens when b is zero. The visual quiz tests understanding of returned values and error handling flow. The snapshot summarizes the Result type usage for functional error handling.

Practice

(1/5)
1. What does the Kotlin Result type represent in functional error handling?
easy
A. A special type of exception thrown during errors
B. An object that holds either a success value or a failure exception
C. A function that always returns a Boolean
D. A list of all errors encountered during execution

Solution

  1. Step 1: Understand the purpose of Result type

    The Result type is designed to wrap either a successful outcome or an error, making error handling explicit and functional.
  2. Step 2: Identify what Result holds

    Result holds either a success value or a failure exception, not a list or a Boolean or an exception thrown directly.
  3. Final Answer:

    An object that holds either a success value or a failure exception -> Option B
  4. Quick Check:

    Result = success or failure [OK]
Hint: Result always wraps success or failure, not exceptions thrown [OK]
Common Mistakes:
  • Thinking Result is an exception type
  • Confusing Result with Boolean return
  • Assuming Result holds multiple errors
2. Which of the following is the correct way to create a successful Result object in Kotlin?
easy
A. Result.makeSuccess(value)
B. Result.ofSuccess(value)
C. Result.createSuccess(value)
D. Result.success(value)

Solution

  1. Step 1: Recall the Kotlin Result API

    Kotlin provides Result.success(value) to create a successful Result wrapping the value.
  2. Step 2: Check method names

    Only Result.success is the correct and existing method; others are invalid.
  3. Final Answer:

    Result.success(value) -> Option D
  4. Quick Check:

    Use Result.success() to wrap success [OK]
Hint: Use Result.success() to wrap success values [OK]
Common Mistakes:
  • Using non-existent methods like Result.ofSuccess
  • Confusing with factory methods
  • Trying to create Result with constructors
3. What will be the output of this Kotlin code?
val result = runCatching { 10 / 0 }
result.onSuccess { println("Success: $it") }
result.onFailure { println("Failure: ${it.message}") }
medium
A. Failure: / by zero
B. Success: 0
C. No output
D. RuntimeException thrown

Solution

  1. Step 1: Understand runCatching behavior

    runCatching executes the block and catches exceptions, wrapping them in Result.failure.
  2. Step 2: Analyze division by zero

    10 / 0 throws an ArithmeticException with message "/ by zero" which is caught and triggers onFailure.
  3. Final Answer:

    Failure: / by zero -> Option A
  4. Quick Check:

    Exception caught triggers onFailure [OK]
Hint: runCatching catches exceptions and calls onFailure [OK]
Common Mistakes:
  • Expecting program to crash with exception
  • Thinking onSuccess runs despite error
  • Ignoring exception message in output
4. Identify the error in this Kotlin code using Result for error handling:
fun divide(a: Int, b: Int): Result<Int> {
    return try {
        Result.success(a / b)
    } catch (e: Exception) {
        Result.failure(e)
    }
}

val result = divide(10, 0)
result.onSuccess { println("Result: $it") }
      .onFailure { println("Error: ${it.message}") }
medium
A. Cannot chain onSuccess and onFailure directly on Result
B. Should catch ArithmeticException instead of Exception
C. Result.failure should not be used inside catch block
D. No error, code works correctly

Solution

  1. Step 1: Check chaining onSuccess and onFailure

    In Kotlin, onSuccess and onFailure are extension functions returning Unit, so chaining them directly causes a compile error.
  2. Step 2: Verify other parts

    Try-catch with Result.success and Result.failure is correct; catching Exception is acceptable; Result.failure is valid.
  3. Final Answer:

    Cannot chain onSuccess and onFailure directly on Result -> Option A
  4. Quick Check:

    onSuccess and onFailure return Unit, no chaining [OK]
Hint: onSuccess/onFailure return Unit, cannot chain calls [OK]
Common Mistakes:
  • Trying to chain onSuccess and onFailure
  • Thinking catch block must catch ArithmeticException only
  • Misusing Result.failure inside catch
5. You want to write a Kotlin function that returns a Result wrapping the parsed integer from a string, or a failure if parsing fails. Which implementation correctly uses Result for this purpose?
hard
A. fun parseInt(str: String): Result<Int> = Result.failure(NumberFormatException())
B. fun parseInt(str: String): Result<Int> = Result.success(str.toIntOrNull() ?: throw NumberFormatException())
C. fun parseInt(str: String): Result<Int> = try { Result.success(str.toInt()) } catch (e: NumberFormatException) { Result.failure(e) }
D. fun parseInt(str: String): Int = str.toIntOrNull() ?: -1

Solution

  1. Step 1: Understand the goal

    The function should return Result wrapping success if parsing works, or failure if it throws NumberFormatException.
  2. Step 2: Analyze each option

    fun parseInt(str: String): Result<Int> = try { Result.success(str.toInt()) } catch (e: NumberFormatException) { Result.failure(e) } uses try-catch to wrap success or failure correctly. fun parseInt(str: String): Result<Int> = Result.success(str.toIntOrNull() ?: throw NumberFormatException()) throws exception outside Result.failure, breaking functional style. fun parseInt(str: String): Result<Int> = Result.failure(NumberFormatException()) always returns failure, ignoring input. fun parseInt(str: String): Int = str.toIntOrNull() ?: -1 returns Int, not Result.
  3. Final Answer:

    fun parseInt(str: String): Result<Int> = try { Result.success(str.toInt()) } catch (e: NumberFormatException) { Result.failure(e) } -> Option C
  4. Quick Check:

    Try-catch with Result.success/failure wraps parsing safely [OK]
Hint: Use try-catch with Result.success and Result.failure for safe parsing [OK]
Common Mistakes:
  • Throwing exceptions instead of wrapping in Result.failure
  • Returning plain Int instead of Result<Int>
  • Always returning failure ignoring input
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard