0
0
Kotlinprogramming~15 mins

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

Choose your learning style9 modes available
Using When as an Expression Returning a Value in Kotlin
📖 Scenario: You are creating a simple program that assigns a message based on a day number. This is like checking the day of the week and giving a friendly note.
🎯 Goal: Build a Kotlin program that uses when as an expression to return a message string based on a day number.
📋 What You'll Learn
Create an integer variable day with the value 3
Create a variable message that uses when as an expression to assign a string based on day
Use when with cases for days 1 to 7, returning the correct day name
Print the message variable
💡 Why This Matters
🌍 Real World
Using <code>when</code> expressions helps in apps to decide actions based on user input or data values, like showing messages or choosing options.
💼 Career
Understanding <code>when</code> expressions is important for Kotlin developers to write clean and readable decision-making code.
Progress0 / 4 steps
1
Create the day variable
Create an integer variable called day and set it to 3.
Kotlin
Need a hint?

Use val day = 3 to create the variable.

2
Set up the when expression
Create a variable called message that uses when as an expression on day. Start the when expression with cases for 1 and 2 returning "Monday" and "Tuesday" respectively.
Kotlin
Need a hint?

Use val message = when(day) { 1 -> "Monday"; 2 -> "Tuesday"; else -> "Unknown" }.

3
Add all days to the when expression
Extend the when expression for message to include all days from 1 to 7 returning "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", and "Sunday" respectively.
Kotlin
Need a hint?

Add all days as cases in the when expression.

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

Use println(message) to show the result.