0
0
Kotlinprogramming~15 mins

When expression as powerful switch in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Using When Expression as a Powerful Switch in Kotlin
📖 Scenario: You are building a simple program that tells the type of a day based on its name. This is like a calendar helper that categorizes days into weekdays or weekends.
🎯 Goal: Build a Kotlin program that uses the when expression to check the name of a day and print whether it is a weekday or weekend.
📋 What You'll Learn
Create a variable with the exact name day and assign it the string value "Monday".
Create a variable with the exact name weekendDays that holds a list of weekend day names: "Saturday" and "Sunday".
Use a when expression with the variable day to check if it is a weekend or a weekday.
Print the exact output "Monday is a Weekday" or similar for the given day.
💡 Why This Matters
🌍 Real World
This kind of day categorization is useful in calendar apps, scheduling software, or any program that needs to treat weekdays and weekends differently.
💼 Career
Understanding <code>when</code> expressions helps you write clear and concise decision-making code, a common task in software development.
Progress0 / 4 steps
1
Create the day variable
Create a variable called day and set it to the string "Monday".
Kotlin
Need a hint?

Use val day = "Monday" to create the variable.

2
Create the weekendDays list
Create a variable called weekendDays and assign it a list containing the strings "Saturday" and "Sunday".
Kotlin
Need a hint?

Use listOf("Saturday", "Sunday") to create the list.

3
Use when expression to check the day type
Use a when expression with the variable day to check if it is in weekendDays. If yes, assign the string "Weekend" to a variable called dayType. Otherwise, assign "Weekday".
Kotlin
Need a hint?

Use when (day) { in weekendDays -> "Weekend" else -> "Weekday" }.

4
Print the result
Print the message in the format: "Monday is a Weekday" using the variables day and dayType with a Kotlin println statement and string template.
Kotlin
Need a hint?

Use println("$day is a $dayType") to print the message.