require to check input. What will be printed when calling checkAge(15)?fun checkAge(age: Int) { require(age >= 18) { "Age must be at least 18" } println("Age is valid: $age") } fun main() { checkAge(15) }
The require function checks the condition and throws IllegalArgumentException with the given message if the condition is false. Since 15 is less than 18, the exception is thrown and the println line is not executed.
check. What error will be raised when calling validateNumber(-5)?fun validateNumber(num: Int) { check(num > 0) { "Number must be positive" } println("Number is valid: $num") } fun main() { validateNumber(-5) }
The check function throws IllegalStateException with the given message if the condition is false. Since -5 is not greater than 0, the exception is thrown.
error("Invalid state"). What is the type of exception thrown and why?fun fail() { error("Invalid state") } fun main() { fail() }
The error() function in Kotlin throws an IllegalStateException with the provided message. It is used to indicate that the program has reached an invalid state.
Option C uses the correct syntax: require(condition) { "message" }. Option C is invalid because require does not take two parameters like that. Options A, B, and C have syntax errors.
processList()?fun processList(): List<Int> { val numbers = listOf(1, 2, 3, 4, 5) return numbers.map { require(it % 2 == 1) { "Only odd numbers allowed" } it * 2 } } fun main() { try { val result = processList() println(result.size) } catch (e: IllegalArgumentException) { println("Exception caught") } }
The require inside map throws an exception when it encounters the first even number (2). This stops the mapping and the exception is caught, printing "Exception caught".