Consider this Kotlin code that uses Result to handle errors functionally. What will it print?
fun divide(a: Int, b: Int): Result<Int> = if (b == 0) Result.failure(ArithmeticException("Division by zero")) else Result.success(a / b) fun main() { val result = divide(10, 0) println(result.getOrElse { _ -> -1 }) }
Look at how getOrElse works when the Result is a failure.
The divide function returns a failure Result when dividing by zero. The getOrElse method returns the success value or the default value if failure. Here, it returns -1 because division by zero fails.
Given this Kotlin code using Result.fold, what will be printed?
fun parseNumber(str: String): Result<Int> = try { Result.success(str.toInt()) } catch (e: NumberFormatException) { Result.failure(e) } fun main() { val result = parseNumber("abc") val output = result.fold( onSuccess = { "Number: $it" }, onFailure = { "Error: ${it.message}" } ) println(output) }
Think about what happens when toInt() fails and how fold handles success and failure.
The parseNumber function returns a failure Result because "abc" is not a valid integer. The fold method calls onFailure lambda, printing the error message.
Analyze this Kotlin code that chains Result operations with map and recover. What will it print?
fun riskyOperation(x: Int): Result<Int> = if (x > 0) Result.success(100 / x) else Result.failure(IllegalArgumentException("x must be positive")) fun main() { val result = riskyOperation(0) .map { it * 2 } .recover<IllegalArgumentException> { _ -> 42 } println(result.getOrNull()) }
Check what recover does when the Result is a failure.
The riskyOperation returns a failure because x is 0. The map is skipped. The recover replaces the failure with success value 42. So getOrNull() returns 42.
What error will this Kotlin code produce when run?
fun main() { val failureResult: Result<Int> = Result.failure(RuntimeException("Failed operation")) println(failureResult.getOrThrow()) }
Look at what getOrThrow() does when the Result is a failure.
The getOrThrow() method throws the exception stored in the failure Result. Here it throws the RuntimeException with message "Failed operation".
Consider this Kotlin code that collects successful results from a list of Result values. How many items will be in the successes list?
fun main() { val results = listOf( Result.success(1), Result.failure(Exception("fail 1")), Result.success(2), Result.failure(Exception("fail 2")), Result.success(3) ) val successes = results.mapNotNull { it.getOrNull() } println(successes.size) }
Remember that getOrNull() returns the value if success, or null if failure.
There are 3 successful Result objects (1, 2, 3). The mapNotNull collects only these values, so the list size is 3.