article banner

Exercise: Days of the week enum

Your task is to create an enum that represents the days of the week and contains a few useful properties and functions. Here are the exact instructions:

  • Define an enum class named DayOfWeek with the following days: MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY.
  • Enum elements should be defined in the order they appear in the week.
  • Enum should define a primary constructor with two properties: isWeekend (of type Boolean) indicating whether the day is a weekend day (Saturday or Sunday) and dayName (of type String) containing the full name of the day.
  • Implement a function named nextDay that takes a DayOfWeek as input and returns the next day in the sequence. For example, if the input is MONDAY, the function should return TUESDAY.

The following code should work:

val friday: DayOfWeek = DayOfWeek.FRIDAY println(friday.dayName) // Friday println(friday.isWeekend) // false val saturday: DayOfWeek = friday.nextDay() println(saturday.dayName) // Saturday println(saturday.isWeekend) // true

This problem can either be solved in the below playground or you can clone kotlin-exercises project and solve it locally. In the project, you can find code template for this exercise in essentials/enums/DayOfWeek.kt. You can find there example usage.

Once you are done with the exercise, you can check your solution here.

Playground

// TODO fun main() { val friday: DayOfWeek = DayOfWeek.FRIDAY println(friday.dayName) // Friday println(friday.isWeekend) // false val saturday: DayOfWeek = friday.nextDay() println(saturday.dayName) // Saturday println(saturday.isWeekend) // true }