0
0
KotlinConceptBeginner · 3 min read

What is Result Type in Kotlin: Simple Explanation and Usage

In Kotlin, the Result type is a special container that holds either a successful value or an error. It helps you handle operations that can succeed or fail without using exceptions directly, making your code cleaner and safer.
⚙️

How It Works

Think of Result as a sealed envelope that can contain either a happy message (a successful value) or a sad message (an error). When you perform an operation that might fail, instead of throwing an exception right away, you put the outcome inside this envelope.

This way, the code that receives the Result can open the envelope and decide what to do next: use the value if it succeeded or handle the error if it failed. This approach avoids crashing your program and makes error handling more explicit and clear.

💻

Example

This example shows how to use Result to safely divide two numbers and handle division by zero without crashing.

kotlin
fun safeDivide(a: Int, b: Int): Result<Int> {
    return if (b == 0) {
        Result.failure(ArithmeticException("Cannot divide by zero"))
    } else {
        Result.success(a / b)
    }
}

fun main() {
    val result1 = safeDivide(10, 2)
    val result2 = safeDivide(10, 0)

    result1.onSuccess { value ->
        println("Success: $value")
    }.onFailure { error ->
        println("Error: ${error.message}")
    }

    result2.onSuccess { value ->
        println("Success: $value")
    }.onFailure { error ->
        println("Error: ${error.message}")
    }
}
Output
Success: 5 Error: Cannot divide by zero
🎯

When to Use

Use Result when you want to handle operations that might fail without throwing exceptions immediately. It is great for functions that do input/output, network calls, or any task where failure is expected and should be handled gracefully.

For example, when reading a file, making a web request, or parsing user input, Result helps you keep your code clean by clearly separating success and failure paths.

Key Points

  • Result holds either a success value or an error.
  • It avoids using exceptions for control flow.
  • Provides clear methods like onSuccess and onFailure to handle outcomes.
  • Improves code readability and safety.

Key Takeaways

Result type safely wraps success or failure outcomes in Kotlin.
Use Result to avoid exceptions and handle errors explicitly.
Result provides easy methods to react to success or failure.
It is ideal for operations that can fail like IO or network calls.