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