0
0
Kotlinprogramming~15 mins

Smart casts in when and if in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Smart casts in when and if
📖 Scenario: Imagine you are building a simple program that checks the type of an input value and responds differently based on whether it is a number or text. This is common when you want to handle different kinds of data safely.
🎯 Goal: You will create a Kotlin program that uses when and if statements with smart casts to check the type of a variable and print messages accordingly.
📋 What You'll Learn
Create a variable called input with a value of type Any that can be either a String or an Int.
Create a variable called threshold with the integer value 10.
Use a when expression to check if input is a String or an Int.
Inside the when branches, use smart casts to access input as String or Int without explicit casting.
If input is an Int, use an if statement to check if it is greater than threshold.
Print appropriate messages for each case.
💡 Why This Matters
🌍 Real World
Programs often receive data of unknown type, like user input or data from the internet. Using smart casts helps safely check and use this data without errors.
💼 Career
Understanding smart casts and type checking is important for Kotlin developers to write clean, safe, and efficient code in Android apps and backend services.
Progress0 / 4 steps
1
Create the input variable
Create a variable called input of type Any and set it to the integer value 15.
Kotlin
Need a hint?

Use val input: Any = 15 to create the variable.

2
Create the threshold variable
Create a variable called threshold and set it to the integer value 10.
Kotlin
Need a hint?

Use val threshold = 10 to create the variable.

3
Use when with smart casts
Write a when expression on input with branches for is String and is Int. Inside each branch, use input as the smart casted type. For the Int branch, add an if statement to check if input is greater than threshold.
Kotlin
Need a hint?

Use when (input) { is String -> ... is Int -> ... } and inside the Int branch use if (input > threshold).

4
Print the result
Run the program and print the output from the when expression.
Kotlin
Need a hint?

Running the program should print: Input is an integer greater than 10