
Today I am going to share about Enum class in Kotlin
- How to create/initialize enum classes
- methods and properties of enum classes.
Initializing enums –
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
enum class Fruits(val color: String) | |
{ | |
APPLE("RED"), | |
BANANA("YELLOW"), | |
GRAPES("GREEN"); | |
} |
Now we can easily access the color of fruits,
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val color = Fruits.GRAPES.color |
- values: This method returns a list of all the constants defined within the enum class.
- valueOf: This methods returns the enum constant defined in enum, matching the input string. If the constant, is not present in the enum, then an IllegalArgumentException is thrown.
Enum Properties-
- ordinal: This property stores the ordinal value of the constant, which is usually a zero-based index.
- name: This property stores the name of the constant.
Below is the example which help us to understand the uses of Enum method and Properties.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Created by Mukesh | |
*/ | |
enum class DAYS { | |
SUNDAY, | |
MONDAY, | |
TUESDAY, | |
WEDNESDAY, | |
THURSDAY, | |
FRIDAY, | |
SATURDAY | |
} | |
fun main() { | |
// A simple demonstration of properties and methods | |
for (day in DAYS.values()) { | |
println("${day.ordinal} = ${day.name}") | |
} | |
println("${DAYS.valueOf("FRIDAY")}") | |
} |
Outputs:
Hope this will help some one.
Enjoy Coding... :)
0 comments:
Post a Comment