Skip to Content
Course content

77: The Result Type for Error Handling

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Why should I use Result instead of just throwing an exception?

Here is the thing about exceptions: they're invisible. If I write a function called fetchUser(id: String), you have no idea just by looking at the signature whether it might throw a UserNotFoundException or a NetworkException. You have to dig into the source code or rely on documentation that might be outdated.

When we return Result<User>, we're making a contract. I'm telling you, "This operation might fail, and you are forced to acknowledge that." It turns a runtime surprise into a compile-time requirement. I personally prefer this because it stops those annoying crashes in production that happen because someone forgot a try-catch block three layers up the call stack.

How do I actually wrap my logic into a Result?

The easiest way to get started is with the runCatching block. It's essentially a fancy wrapper around a try-catch that returns a Result object instead of letting the exception fly. Let's look at a real-world example of fetching a user profile from a flaky API:

data class UserProfile(val name: String, val email: String)

class UserRepository {
    fun getUserProfile(userId: String): Result<UserProfile> {
        return runCatching {
            // Imagine this calls a network library that might throw an IOException
            if (userId == "unknown") throw Exception("User not found in database")
            UserProfile("Jane Doe", "jane@example.com")
        }
    }
}

Notice how clean that is. I don't have to manually create Result.success() or Result.failure() calls; runCatching handles the plumbing for me. If the block completes, it's a success; if it throws, it's a failure.

What's the best way to handle the result without a mess of if-statements?

This is where Result really shines. You can chain operations together. If you just want to do something on success and something else on failure, onSuccess and onFailure are your best friends. But if you need to transform the result into a final value (like a UI string), fold is the way to go.

Check out how I'd handle the UserProfile fetch in a ViewModel or a Controller:

val repository = UserRepository()
val result = repository.getUserProfile("123")

// Option 1: Side-effect style
result.onSuccess { user -> 
    println("Welcome back, ${user.name}!") 
}.onFailure { error -> 
    println("Error: ${error.message}") 
}

// Option 2: Transformation style (fold)
val displayMessage = result.fold(
    onSuccess = { user -> "User: ${user.name}" },
    onFailure = { "Could not load profile. Please try again." }
)

I love fold because it forces you to handle both paths. You can't just "forget" the error case. If you just need a fallback value, you can also use getOrElse { ... }, which is incredibly handy for providing defaults.




📋 Practical Task

Implement a Robust Bank Transfer System

You are building a simple banking module. Your task is to create a function that transfers money between two accounts. Instead of throwing exceptions, you must use the Result type to handle potential failures.

Requirements:

  • Create an Account data class with a balance property.
  • Implement a function transferMoney(from: Account, to: Account, amount: Double): Result<Double>.
  • The function should return a failure if:
    • The amount is negative.
    • The from account has insufficient funds.
  • If successful, it should return the new balance of the from account wrapped in a success.
  • In your main function, call transferMoney and use fold to print either a "Transfer Successful" message with the remaining balance or a "Transfer Failed" message with the specific error.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.