runCatching. What will it print?val result = runCatching { val number = "123a".toInt() number * 2 }.getOrElse { -1 } println(result)
The string "123a" cannot be converted to an integer, so toInt() throws a NumberFormatException. The runCatching catches this exception, and getOrElse returns the fallback value -1.
runCatching. What is the value of output?val output = runCatching { val list = listOf(1, 2, 3) list[5] }.getOrNull() println(output)
Accessing list[5] throws an IndexOutOfBoundsException. runCatching catches it, so getOrNull() returns null.
val result = runCatching { throw IllegalStateException("Error happened") }.getOrElse { throw it } println("Done")
The runCatching catches the exception, but getOrElse rethrows it with throw it. So the exception is not handled and crashes the program.
getOrElse returns the result if successful, or the lambda value if an exception occurred. ?: operator does not work directly on Result. getOrNull returns null on failure, so the Elvis operator works but returns null if success is null.
results contain after execution?val inputs = listOf("10", "abc", "20", "-5") val results = inputs.mapNotNull { input -> runCatching { input.toInt() } .getOrNull() }.filter { it > 0 }
"10" and "20" convert successfully to positive integers. "abc" fails and returns null, "-5" converts but is filtered out because it is not > 0. So the final list has 2 items.