0
0
Kotlinprogramming~15 mins

Preconditions (require, check, error) in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Preconditions in Kotlin with require, check, and error
📖 Scenario: You are building a simple Kotlin program that processes user input for an online store. You want to make sure the input values are valid before continuing.
🎯 Goal: Learn how to use Kotlin's require, check, and error functions to validate input and handle errors clearly.
📋 What You'll Learn
Create variables with exact names and values as instructed
Use require to check input preconditions
Use check to verify internal state
Use error to throw an exception with a message
Print the final valid message
💡 Why This Matters
🌍 Real World
Preconditions help ensure that your program only runs with valid data, preventing bugs and crashes early.
💼 Career
Many jobs require writing safe and reliable code that checks inputs and internal states using preconditions and error handling.
Progress0 / 4 steps
1
Set up user input variables
Create a variable called username and set it to the string "Alice". Create another variable called age and set it to the integer 25.
Kotlin
Need a hint?

Use val to create variables with the exact names and values.

2
Add precondition checks with require
Use require to check that username is not empty with the message "Username cannot be empty". Use require to check that age is greater than or equal to 18 with the message "Age must be at least 18".
Kotlin
Need a hint?

Use require(condition) { "message" } to check input values.

3
Check internal state with check and throw error
Use check to verify that username starts with an uppercase letter with the message "Username must start with uppercase". If age is greater than 100, use error to throw an exception with the message "Age is unrealistically high".
Kotlin
Need a hint?

Use check(condition) { "message" } for internal checks and error("message") to throw exceptions.

4
Print confirmation message
Print the message "User Alice is valid and age 25 is accepted." using println.
Kotlin
Need a hint?

Use println("message") to show the final confirmation.