Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
77: The Result Type for Error Handling
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
Accountdata class with abalanceproperty. - Implement a function
transferMoney(from: Account, to: Account, amount: Double): Result<Double>. - The function should return a
failureif:- The
amountis negative. - The
fromaccount has insufficient funds.
- The
- If successful, it should return the new balance of the
fromaccount wrapped in asuccess. - In your
mainfunction, calltransferMoneyand usefoldto print either a "Transfer Successful" message with the remaining balance or a "Transfer Failed" message with the specific error.
There are no comments for now.