0
0
Kotlinprogramming~20 mins

Result type for functional error handling in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Result Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Kotlin code using Result?

Consider this Kotlin code that uses Result to handle errors functionally. What will it print?

Kotlin
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 })
}
AException in thread "main" java.lang.ArithmeticException: Division by zero
B0
C-1
D10
Attempts:
2 left
💡 Hint

Look at how getOrElse works when the Result is a failure.

Predict Output
intermediate
2:00remaining
What does this Kotlin code print when using Result.fold?

Given this Kotlin code using Result.fold, what will be printed?

Kotlin
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)
}
AError: For input string: "abc"
BNumber: abc
CNumber: 0
DException in thread "main" java.lang.NumberFormatException: For input string: "abc"
Attempts:
2 left
💡 Hint

Think about what happens when toInt() fails and how fold handles success and failure.

Predict Output
advanced
2:00remaining
What is the output of this Kotlin code chaining Result operations?

Analyze this Kotlin code that chains Result operations with map and recover. What will it print?

Kotlin
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())
}
A200
B0
CException in thread "main" java.lang.IllegalArgumentException: x must be positive
D42
Attempts:
2 left
💡 Hint

Check what recover does when the Result is a failure.

Predict Output
advanced
2:00remaining
What error does this Kotlin code raise when accessing Result's value?

What error will this Kotlin code produce when run?

Kotlin
fun main() {
    val failureResult: Result<Int> = Result.failure(RuntimeException("Failed operation"))
    println(failureResult.getOrThrow())
}
AIllegalStateException
BRuntimeException: Failed operation
CNoSuchElementException
DNullPointerException
Attempts:
2 left
💡 Hint

Look at what getOrThrow() does when the Result is a failure.

🧠 Conceptual
expert
2:00remaining
How many items are in the resulting list after this Kotlin Result sequence?

Consider this Kotlin code that collects successful results from a list of Result values. How many items will be in the successes list?

Kotlin
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)
}
A3
B2
C5
D0
Attempts:
2 left
💡 Hint

Remember that getOrNull() returns the value if success, or null if failure.