What is the method for declaring enum classes in Kotlin…

In Kotlin, the method of declaring an enum class is to use the enum class keyword.

The sample code is shown as follows:

enum class DayOfWeek {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
}

In the code above, DayOfWeek is an enum class that includes seven enum constants: MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, and SUNDAY.

You can use an enumeration class just like how you would use any other class, for example:

val today = DayOfWeek.MONDAY
println(today) // 输出:MONDAY

You can also add properties and methods to enum constants, for example:

enum class DayOfWeek(val dayNumber: Int) {
    MONDAY(1),
    TUESDAY(2),
    WEDNESDAY(3),
    THURSDAY(4),
    FRIDAY(5),
    SATURDAY(6),
    SUNDAY(7);

    fun isWeekend(): Boolean {
        return this == SATURDAY || this == SUNDAY
    }
}

val today = DayOfWeek.MONDAY
println(today.isWeekend()) // 输出:false

In the code above, the enum class DayOfWeek has been enhanced with a dayNumber property and an isWeekend() method.

bannerAds