Menu
Coddy logo textTech

Try as an Expression

Part of the Logic & Flow section of Coddy's Kotlin journey. Lesson 53 of 63.

A try/catch can produce a value: the last expression of the completed try block or matching catch block is its result. A finally block runs afterward for cleanup but its last expression does not replace that value. Keep cleanup separate from the calculation.

Inside main:

val value = try { "bad".toInt() } catch (error: NumberFormatException) { -1 }
println(value)

The matching catch provides minus one as the expression result.

A try expression takes its value from the completed try or catch branch.

challenge icon

Challenge

Medium

Complete parsedDouble with parameters text: String. Use a try expression to parse text as Int and double it. Catch NumberFormatException and use -1. Successfully parsed inputs are between -1000 and 1000; invalid and out-of-range strings may also appear. Do not trim.

Unless stricter bounds are stated above, collections contain at most 100 elements at each level, and integer arguments and integer collection values are between -1000 and 1000. Text supplied for parsing can include invalid or out-of-range representations as described.

Return a value of type Int. Keep the supplied input/output code. It reads scalar arguments one per line; a list starts with its count followed by its elements, and a map starts with its entry count followed by each key and value. Nested lists repeat the count-and-elements format for each row. The supplied main prints the return value followed by one newline. Lists use Kotlin's standard bracketed format; print no additional labels.

Try it yourself

fun parsedDouble(text: String): Int {
    // Write your solution here.
    return 0
}
fun main() {
    val text = readLine().orEmpty()
    println(parsedDouble(text))
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Kotlin playground