Bird
Raised Fist0
Kotlinprogramming~20 mins

Preconditions (require, check, error) in Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Preconditions 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 require?
Consider this Kotlin function that uses require to check input. What will be printed when calling checkAge(15)?
Kotlin
fun checkAge(age: Int) {
    require(age >= 18) { "Age must be at least 18" }
    println("Age is valid: $age")
}

fun main() {
    checkAge(15)
}
AException in thread "main" java.lang.IllegalArgumentException: Age must be at least 18
BNo output, program ends silently
CException in thread "main" java.lang.IllegalStateException: Age must be at least 18
DAge is valid: 15
Attempts:
2 left
💡 Hint
Remember that require throws IllegalArgumentException if the condition is false.
❓ Predict Output
intermediate
2:00remaining
What error does this Kotlin code raise using check?
Look at this Kotlin function using check. What error will be raised when calling validateNumber(-5)?
Kotlin
fun validateNumber(num: Int) {
    check(num > 0) { "Number must be positive" }
    println("Number is valid: $num")
}

fun main() {
    validateNumber(-5)
}
AException in thread "main" java.lang.IllegalArgumentException: Number must be positive
BException in thread "main" java.lang.IllegalStateException: Number must be positive
CNumber is valid: -5
DNo output, program ends silently
Attempts:
2 left
💡 Hint
Check throws IllegalStateException if the condition is false.
🔧 Debug
advanced
2:00remaining
Why does this Kotlin code using error() crash with this message?
This Kotlin function calls error("Invalid state"). What is the type of exception thrown and why?
Kotlin
fun fail() {
    error("Invalid state")
}

fun main() {
    fail()
}
AThrows java.lang.IllegalStateException with message "Invalid state" because error() always throws this exception.
BThrows java.lang.IllegalArgumentException with message "Invalid state" because error() throws this exception.
CThrows java.lang.RuntimeException with message "Invalid state" because error() throws a generic runtime exception.
DNo exception thrown, error() just logs the message.
Attempts:
2 left
💡 Hint
Check the Kotlin documentation for error() function behavior.
📝 Syntax
advanced
2:00remaining
Which Kotlin code snippet correctly uses require with a message lambda?
Select the code that compiles and runs without syntax errors.
Arequire(x > 0) -> { "x must be positive" }
Brequire(x > 0, "x must be positive")
Crequire(x > 0) { "x must be positive" }
Drequire(x > 0) "x must be positive"
Attempts:
2 left
💡 Hint
require can take a lambda that returns the message.
🚀 Application
expert
2:00remaining
How many items are in the list after filtering with require in this Kotlin code?
This Kotlin code filters a list using require inside a map. How many items remain after running processList()?
Kotlin
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")
    }
}
A0
B3
C5
DException caught
Attempts:
2 left
💡 Hint
require throws exception on first even number, stopping the map.

Practice

(1/5)
1. What is the primary purpose of the require function in Kotlin?
easy
A. To log warnings without stopping the program
B. To verify the internal state of the program
C. To stop the program immediately with an error message
D. To check if function arguments meet certain conditions

Solution

  1. Step 1: Understand require usage

    require is used to check if the inputs to a function are valid before proceeding.
  2. Step 2: Differentiate from other preconditions

    check is for program state, and error stops the program immediately. require is specifically for argument validation.
  3. Final Answer:

    To check if function arguments meet certain conditions -> Option D
  4. Quick Check:

    require = argument check [OK]
Hint: Require checks function inputs are valid before running [OK]
Common Mistakes:
  • Confusing require with check for program state
  • Thinking error is for argument validation
  • Assuming require stops program immediately
2. Which of the following is the correct syntax to use check in Kotlin to verify a condition with a lazy message?
easy
A. check(value > 0, "Value must be positive")
B. check { value > 0, "Value must be positive" }
C. check(value > 0) { "Value must be positive" }
D. check(value > 0); "Value must be positive"

Solution

  1. Step 1: Recall check function signature

    check takes a Boolean condition and a lambda returning a message string if false.
  2. Step 2: Match syntax with options

    check(value > 0) { "Value must be positive" } uses check(condition) { "message" } which is correct Kotlin syntax.
  3. Final Answer:

    check(value > 0) { "Value must be positive" } -> Option C
  4. Quick Check:

    check syntax = condition + lambda message [OK]
Hint: Use check(condition) { "message" } syntax [OK]
Common Mistakes:
  • Passing message as second argument instead of lambda
  • Using comma inside lambda incorrectly
  • Omitting braces for message lambda
3. What will be the output of this Kotlin code?
fun test(x: Int) {
    require(x > 0) { "x must be positive" }
    check(x < 10) { "x must be less than 10" }
    println("x is valid: $x")
}

test(15)
medium
A. IllegalStateException: x must be less than 10
B. IllegalArgumentException: x must be positive
C. No output, program stops silently
D. x is valid: 15

Solution

  1. Step 1: Evaluate require(x > 0)

    Since 15 > 0, require passes without exception.
  2. Step 2: Evaluate check(x < 10)

    15 is not less than 10, so check throws IllegalStateException with message "x must be less than 10".
  3. Final Answer:

    IllegalStateException: x must be less than 10 -> Option A
  4. Quick Check:

    require passes, check fails with IllegalStateException [OK]
Hint: Require checks args, check checks state; exception shows which failed [OK]
Common Mistakes:
  • Thinking require throws error for x=15
  • Assuming println runs after failed check
  • Confusing exception types thrown by require and check
4. Identify the error in this Kotlin code snippet:
fun validate(name: String) {
    require(name.isNotEmpty(), "Name cannot be empty")
    check(name.length > 3) { "Name too short" }
}
medium
A. check condition should be inside require
B. No error, code is correct
C. require should not have a message
D. Incorrect use of require with message as second argument

Solution

  1. Step 1: Review require syntax

    Both require(condition, "message") (eager message) and require(condition) { "message" } (lazy message) are valid overloads.
  2. Step 2: Review check syntax

    The lambda syntax for check is also valid. The code compiles and works as expected.
  3. Final Answer:

    No error, code is correct -> Option B
  4. Quick Check:

    Both eager and lazy messages valid [OK]
Hint: require/check support both eager message and lazy lambda [OK]
Common Mistakes:
  • Thinking comma message is invalid for require
  • Confusing require syntax with only lambda support
  • Forgetting that multiple overloads exist
5. You want to stop your Kotlin program immediately with a custom error message if a critical condition fails.
fun criticalCheck(flag: Boolean) {
    // Your code here
}
hard
A. Use error("Critical failure") if flag is false
B. Use require(flag == false) { "Critical failure" }
C. Use check(flag == false) { "Critical failure" }
D. Use println("Critical failure") and continue

Solution

  1. Step 1: Understand error function purpose

    error immediately throws an IllegalStateException with the given message and stops the program.
  2. Step 2: Apply error for critical failure

    Use if (!flag) error("Critical failure") to stop execution immediately when condition fails.
  3. Final Answer:

    Use error("Critical failure") if flag is false -> Option A
  4. Quick Check:

    error stops program immediately with message [OK]
Hint: Use error() to stop program immediately with message [OK]
Common Mistakes:
  • Using require or check which throw exceptions but may be caught
  • Printing message without stopping program
  • Not stopping program on critical failure
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard