0
0
Kotlinprogramming~30 mins

When with ranges and types in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Using When with Ranges and Types in Kotlin
📖 Scenario: You are building a simple program that categorizes input values based on their type and numeric range. This is useful in many apps where you want to respond differently depending on what kind of data you get and its value.
🎯 Goal: Create a Kotlin program that uses a when expression to check both the type and the numeric range of a variable, then prints a message describing the input.
📋 What You'll Learn
Create a variable called input with a specific value.
Create a variable called ageRange representing ages from 13 to 19 inclusive.
Use a when expression to check the type of input and if it is an Int, check if it falls within ageRange.
Print the correct message based on the checks.
💡 Why This Matters
🌍 Real World
Checking input types and ranges is common in apps that need to validate user data, like age verification or input validation.
💼 Career
Understanding how to use <code>when</code> with types and ranges helps you write clear and concise Kotlin code for decision making, a key skill for Android and backend Kotlin developers.
Progress0 / 4 steps
1
Create the input variable
Create a variable called input and set it to the integer value 16.
Kotlin
Need a hint?

Use val input: Any = 16 to allow different types later.

2
Create the ageRange variable
Create a variable called ageRange that represents the range of integers from 13 to 19 inclusive.
Kotlin
Need a hint?

Use the range operator .. to create the range.

3
Write the when expression to check type and range
Write a when expression using the variable input that checks:
- If input is an Int and is in ageRange, print "Teenager".
- If input is an Int but not in ageRange, print "Not a teenager".
- If input is a String, print "Input is a string".
- For any other type, print "Unknown type".
Kotlin
Need a hint?

Use is to check type and in to check if number is in range.

4
Print the result
Run the program to print the correct message based on the input value and the when expression.
Kotlin
Need a hint?

Running the program should print "Teenager" because 16 is in the range 13 to 19.