← Back to Kotlin Course | Chapter 13: Error Handling & Testing | Lesson 3 of 6

Result Type क्या है

Result type एक box है जो या तो एक सफल जवाब रखता है या इसके बजाय हुई error रखता है, कभी throw किए बिना।
Syntax
kotlin
val result = runCatching { riskyCall() }

result.getOrNull()
result.getOrElse { default }
result.fold(
    onSuccess = { value -> /* ... */ },
    onFailure = { error -> /* ... */ }
)

Creating a Result with runCatching

runCatching { } code का एक block execute करता है और outcome को एक Result में wrap कर देता है: एक पकड़ा गया exception एक failure बन जाता है, और एक normal return value एक success बन जाती है।

उदाहरण: Creating a Result with runCatching

markup
// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `result`, set to `runCatching { "42".toInt() }`
    val result = runCatching { "42".toInt() }
    // Print "Success: ${result.isSuccess}" to the console, with a trailing newline
    println("Success: ${result.isSuccess}")
}

Extracting Values Safely

.getOrNull() successful value या failure पर null return करता है, जबकि .getOrElse { } आपको failure से ही compute की गई एक fallback देने देता है।

उदाहरण: Extracting Values Safely

markup
// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `goodResult`, set to `runCatching { "42".toInt() }`
    val goodResult = runCatching { "42".toInt() }
    // Declare a read-only variable `badResult`, set to `runCatching { "abc".toInt() }`
    val badResult = runCatching { "abc".toInt() }
    // Print "Good: ${goodResult.getOrNull()}" to the console, with a trailing newline
    println("Good: ${goodResult.getOrNull()}")
    // Print "Bad with fallback: ${badResult.getOrElse { -1 }}" to the console, with a trailing newline
    println("Bad with fallback: ${badResult.getOrElse { -1 }}")
}

Handling Both Outcomes with fold

.fold(onSuccess, onFailure) आपको एक expression में एक success और एक failure case दोनों साथ handle करने देता है, किसी भी branch से एक single unified result produce करते हुए।

उदाहरण: Handling Both Outcomes with fold

markup
// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `result`, set to `runCatching { "abc".toInt() }`
    val result = runCatching { "abc".toInt() }
    val message = result.fold(
        onSuccess = { "Parsed: $it" },
        onFailure = { "Failed: ${it.message}" }
    )
    // Print `message` to the console, with a trailing newline
    println(message)
}

Result in Function Return Types

कोई function throw करने के बजाय सीधे Result<T> return कर सकता है, failure को उसके return type का एक explicit, दिखाई देने वाला हिस्सा बनाते हुए जिसे callers को सोच-समझकर handle करना चाहिए। (एक explicit function return type के रूप में Result declare करने के लिए Kotlin 1.5+ चाहिए; पुराने versions पर वही value अब भी compute होकर एक val में store की जा सकती है, जैसा नीचे दिखाया गया है।)

उदाहरण: Result in Function Return Types

markup
// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `input`, set to `"-5"`
    val input = "-5"
    // Call `runCatching` with a trailing lambda, storing the result in `result`
    val result: Result<Int> = runCatching {
        // Declare a read-only variable `age`, set to `input.toInt()`
        val age = input.toInt()
        require(age >= 0) { "Age cannot be negative" }
        age
    }
    // Print `result.fold(onSuccess = { "Age: $it" }, onFailure = { "Invalid: ${it.message}" })` to the console, with a trailing newline
    println(result.fold(onSuccess = { "Age: $it" }, onFailure = { "Invalid: ${it.message}" }))
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह भूल जाना कि Result exceptions के एक return-value विकल्प के रूप में डिज़ाइन किया गया है, खुद throw करने वाले code को call करते समय try/catch उपयोग करने का विकल्प नहीं।
  2. .isSuccess/.isFailure न जांचना (या .fold/.getOrElse उपयोग न करना) और इसके बजाय तुरंत .getOrThrow() call करना, non-throwing result का मकसद हराते हुए।
  3. यह मान लेना कि Result किसी भी तरह की computation state (जैसे 'still loading') रख सकता है; यह सख्ती से success या failure represent करता है, कोई दूसरी states नहीं।
चैप्टर सारांश
  • Result<T> call site पर किसी try/catch की ज़रूरत के बिना या तो एक successful value या एक failure represent करता है।
  • runCatching { } एक block चलाता है और इसके outcome को एक Result में wrap करता है, किसी भी फेंके गए exception को failure case में पकड़ते हुए।
  • .getOrNull(), .getOrElse { }, और .getOrThrow() किसी Result से value को अलग-अलग तरीकों से निकालते हैं।
  • .fold(onSuccess, onFailure) किसी Result के दोनों outcomes को एक single expression में handle करता है।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.