0
0
Kotlinprogramming~15 mins

If as an expression returning value in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Using If as an Expression Returning Value in Kotlin
📖 Scenario: Imagine you are creating a simple program that decides what message to show based on the temperature outside. You want to use Kotlin's if expression to choose the message.
🎯 Goal: Build a Kotlin program that uses if as an expression to assign a message based on a temperature value.
📋 What You'll Learn
Create an integer variable called temperature with the value 15
Create a string variable called message that uses if as an expression to set its value
Use if to check if temperature is greater than 20
If true, message should be "It's warm outside!"
If false, message should be "It's cold outside!"
Print the message variable
💡 Why This Matters
🌍 Real World
Using <code>if</code> as an expression helps in many real-world apps where decisions affect what data or message to show.
💼 Career
Understanding expressions like <code>if</code> in Kotlin is important for writing clean, efficient code in Android app development and backend services.
Progress0 / 4 steps
1
Create the temperature variable
Create an integer variable called temperature and set it to 15.
Kotlin
Need a hint?

Use val temperature = 15 to create the variable.

2
Create the message variable using if expression
Create a string variable called message that uses if as an expression to set its value. Use if (temperature > 20) to assign "It's warm outside!" if true, otherwise "It's cold outside!".
Kotlin
Need a hint?

Use val message = if (temperature > 20) "It's warm outside!" else "It's cold outside!".

3
Print the message
Write a println statement to print the message variable.
Kotlin
Need a hint?

Use println(message) to show the message on the screen.

4
Run the program and see the output
Run the program and observe the output. It should print "It's cold outside!" because the temperature is 15.
Kotlin
Need a hint?

Check that the output matches exactly: "It's cold outside!"