. f Kotlin - Enum Classes in Kotlin | Enum Methods | Enum Properties ~ Android Developers Blog

Monday, 11 May 2020

Kotlin - Enum Classes in Kotlin | Enum Methods | Enum Properties

Hello Friend,
              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 –

enum class Fruits(val color: String)
{
APPLE("RED"),
BANANA("YELLOW"),
GRAPES("GREEN");
}
view raw gistfile1.txt hosted with ❤ by GitHub

Now we can easily access the color of fruits,
val color = Fruits.GRAPES.color
view raw gistfile1.txt hosted with ❤ by GitHub
Enum Methods-

  1. values: This method returns a list of all the constants defined within the enum class.
  2. 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-

  1. ordinal: This property stores the ordinal value of the constant, which is usually a zero-based index.
  2. 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.
/**
* 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")}")
}
view raw Enum.kt hosted with ❤ by GitHub
Outputs:

Hope this will help some one.
Enjoy Coding... :)

Mukesh Kumar

Hi Guys I am from Delhi working as Web/Mobile Application Developer(Android Developer), also have knowledge of Roboelctric and Mockito ,android test driven development... Blogging has been my passion and I think blogging is one of the powerful medium to share knowledge and ideas....

0 comments:

Post a Comment

 

Copyright @ 2013 Android Developers Blog.