Menu
Coddy logo textTech

Validating with Require

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

require(condition) checks a function argument contract. If the condition is false, it throws IllegalArgumentException. A trailing lambda can supply an error message. Catching that expected error at the caller lets you translate invalid input into a defined result.

fun ticketCost(count: Int): Int {
    require(count >= 0) { "count must be nonnegative" }
    return count * 5
}

Inside main:

try {
    println(ticketCost(-2))
} catch (error: IllegalArgumentException) {
    println("invalid")
}

The failed argument requirement throws before the cost is calculated.

require throws IllegalArgumentException when its condition is false.

challenge icon

Challenge

Medium

Complete validatedCost with parameters count: Int. Use the supplied cost helper, which requires a nonnegative count. Return the cost as a string on success, or invalid if IllegalArgumentException is thrown. count is between -1000 and 1000.

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 String. 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 cost(count: Int): Int {
    require(count >= 0) { "count must be nonnegative" }
    return count * 5
}
fun validatedCost(count: Int): String {
    // Write your solution here.
    return ""
}
fun main() {
    val count = readln().toInt()
    println(validatedCost(count))
}
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