Enums are predefined compile-time constants that contain predefined constants.
Kotlin Enum Syntax and Example
An Enum class is a custom class defined by a group of constants.
CONSTANTS can be of any type with optional values, and these constants are separated by commas.
Each constant is of the Data type Enum_Class.
enum class Enum_Class{
CONSTANT1[(Optionalvalue)],
CONSTANT2[(Optionalvalue)],
CONSTANT3[(Optionalvalue)],
....
CONSTANTN[(Optionalvalue)],
}
Here is an example
enum class Weekend {
SATURDAY, SUNDAY
}
Kotlin Enum with Int values initialization
The enum class contains constants initialized with values.
class declaration must contain a datatype parameter to define the value.
Below Kotlin class is declared with an int value and each constant is initialized with an int value.
enum class Weekend(val value: Int) {
SATURDAY(0), SUNDAY(1)
}
## Kotlin Enum with String values initialization
Enum class types c
enum class Status(val type: String) {
INVITED("invite"),
ACTIVATED("active"),
DELETED("delete"),
}
How to get String or Int value from an Enum?
Create a function, take the Enum class object, and return the String value of it.
fun getStringValue(status: Status): String {
return status.str;
}
getStringValue()
function is called inside the main function by passing an Enum constant.
Here is an example
fun main() {
println(getStringValue(Status.INVITED))
}
enum class Status(val str: String) {
INVITED("invite"),
ACTIVATED("active"),
DELETED("delete"),
}
fun getStringValue(status: Status): String {
return status.str;
}
Kotlin Enum Class iterate values
There are multiple ways, can iterate Enum class constants.
Enum class has a ‘values()’ method that returns an array of constants.
import java.util.Arrays
enum class Weekend {
SATURDAY, SUNDAY
}
fun main() {
val weekends = Weekend.values()
println(weekends.contentToString())
}
Another way is enumValues<Enum>
which returns an array of constants.
import java.util.Arrays
enum class Weekend {
SATURDAY, SUNDAY
}
fun main() {
val weekends = enumValues<Weekend>()
println(weekends.contentToString())
}
Another way Using for Loop
The values()
function returns an array, uses the forEach
loop with a lambda expression to loop the element, and prints it.
Simplified, using method references to call the println function
import java.util.Arrays
enum class Weekend {
SATURDAY, SUNDAY
}
fun main() {
val weekends = Weekend.values()
// lambda expression forEach
Weekend.values().forEach { println(it) }
// method reference
Weekend.values().forEach(::println)
}