Read Enum Value From Argument in Java

A useful characteristic while programming is having the ability to indicate that a variable merely has a finite set of possible values. To accomplish this, near programming languages introduced the concept of enumerations.

Although enumerations usually represent just a mere named list of predefined constant values, Kotlin enums are much more than than that. In fact, they are real classes, and not uncomplicated types or limited information structured.

This translates to the fact that they can have custom properties and methods, implement interfaces, use anonymous classes, and much more. Thus, Kotlin enum classes play a crucial part in the language.

Plus, employing enums makes your code more readable and less error-prone. This is why every Kotlin developer should know how to use them. And then, let'south dive into enum classes and see everything y'all demand to learn to primary them.

Kotlin enum classes vs. Java enum types

In Java, enums are types. Specifically, the official documentation defines an enum type as "a special data type that enables a variable to be a set up of predefined constants." This means that the aforementioned variable must be equal to one of the predefined values. These values are constants, and represent the backdrop of the enum type.

Despite being a type, the Coffee enum declaration really creates a form behind the scenes. Thus, Java enums can include custom methods and backdrop. This, in addition to the default ones automatically added by the compiler. That's information technology — nix more tin be done with Coffee enum types.

Unlike what happens in Java, Kotlin enums are classes natively, and not but behind the scenes. This is why they are called enum classes, as opposed to Java enum types. That prevents developers from considering them every bit just mere collections of constants, every bit may happen in Java.

As we are about to see, Kotlin enums are much more than that. Not only can they use anonymous classes, merely also implement interfaces, just similar any other Kotlin course. And then, let'due south forget Coffee enum types and beginning delving into Kotlin enum classes.

Basic features of Kotlin enums

Let's start exploring the most common features offered by Kotlin enums.

Defining enums

The most bones use case for Kotlin enum classes is to treat them as collections of constants. In this example, they are called type-safety enums and can be divers as follows:

enum class Day {        Monday,      TUESDAY,     Wednesday,      THURSDAY,      FRIDAY,      Sat,     SUNDAY }        

As you can see, the enum keyword is followed by the course keyword. This should prevent you lot from being fooled into thinking that Kotlin enums are mere types.

Then comes the enum class proper noun. Finally, within the body of the enum class, the possible comma-separated options called enum constants. Note that since they are constants, their names should always exist in capital letters. This is what the simplest Kotlin enum class consists of.

Initializing enums

Kotlin enums are classes, which ways that they tin have ane or more than constructors. Thus, yous can initialize enum constants by passing the values required to one of the valid constructors. This is possible considering enum constants are nil other than instances of the enum class itself.
Let'south see how this works through an example:

enum class Day(val dayOfWeek: Int) {         MONDAY(1),      TUESDAY(2),     Midweek(3),      THURSDAY(4),      Fri(5),      Saturday(six),     Lord's day(seven) }        

This way, each enum constant is associated with the relative number of the day of the calendar week.

Unremarkably, the constructor-based approach is used to provide enum constants with useful information or meaningful values. On of the most common cases is to provide them with a custom printableName property. This is very useful when printing them, and can exist accomplished as follows:

enum class 24-hour interval(val printableName: Cord) {         Monday("Monday"),      TUESDAY("Tuesday"),     WEDNESDAY("Wednesday"),      Thursday("Thursday"),      Friday("Friday"),      SATURDAY("Saturday"),     Dominicus("Sunday") }        

Inbuilt backdrop

Kotlin enum classes come with a few inbuilt properties. Just like what happens in Java, they are automatically added to each enum class by the compiler. So, you tin can access them in whatsoever enum course instance. Permit's see them all:

  1. ordinal
    ordinal allows you to retrieve where the current enum constant appears in the list. It is a zero-based index, which means that the showtime constant in the options list has value 0, the second i, and and so on. When implementing the Comparable interface, this property will be used in sorting logic.
  2. name
    name returns the proper name of the enum constant equally a string.

Permit's see these 2 in activeness through the post-obit instance:

enum grade 24-hour interval(val dayOfWeek: Int) {     Mon(i),      TUESDAY(2),     WEDNESDAY(three),      Thursday(iv),      Friday(5),      Sabbatum(half dozen),     SUNDAY(7) }  fun main() {         for (day in Solar day.values())         println("[${day.ordinal}] -> ${day.proper name} (${day.dayOfWeek}^ day of the calendar week)") }        

By running this code, you lot would become the following outcome:

[0] -> MONDAY (1^ solar day of the week) [1] -> TUESDAY (2^ solar day of the calendar week) [2] -> WEDNESDAY (3^ day of the week) [3] -> THURSDAY (4^ day of the week) [4] -> FRIDAY (5^ day of the week) [five] -> SATURDAY (6^ day of the week) [6] -> Dominicus (7^ day of the week)        

As you can see, the cord returned by the proper noun inbuilt property coincides with the constant itself. This does not make them very printable, and this is why adding a custom printableName property might be useful.

Also, this example highlights why adding a custom index might exist required likewise. This is because ordinal is a zero-based index meant to be used while programming rather than to provide advisory content.

Advanced features of Kotlin enums

At present, information technology is fourth dimension to delve into the most advanced and complicated features offered by Kotlin enum classes.

Calculation custom properties and methods

Custom properties and methods tin be added to enum classes, just like in any other Kotlin class. What changes is the syntax, which must follow specific rules.

In particular, methods and properties must be added beneath the enum constants definition, later a semicolon. Just similar any other property in Kotlin, you tin provide them with a default value. Plus, enum classes tin can have both example and static methods:

enum grade Solar day {     MONDAY(1, "Monday"),     TUESDAY(2, "Tuesday"),     Midweek(iii, "Wednesday"),     THURSDAY(iv, "Thursday"),     FRIDAY(five, "Friday"),     SATURDAY(6, "Saturday"),     Sun(vii, "Sunday"); // end of the constants      // custom properties with default values     var dayOfWeek: Int? = zilch     var printableName : Cord? = aught      constructor()      // custom constructors     constructor(         dayOfWeek: Int,         printableName: String     ) {         this.dayOfWeek = dayOfWeek         this.printableName = printableName     }      // custom method     fun customToString(): String {         return "[${dayOfWeek}] -> $printableName"     } }        

In this instance, a custom constructor, ii custom properties, and a custom example method were added to the enum grade. Backdrop and methods tin can be accessed through instances, which are the enum constants, with the following syntax:

// accessing the dayOfWeek belongings Solar day.MONDAY.dayOfWeek  // accessing the customToString() method Mean solar day.MONDAY.customToString()        

Keep in mind that Kotlin does non have the concept of static methods. Even so, the same result can be achieved past harnessing companion objects, which are supported by Kotlin enum classes. Methods defined inside companion objects practice not depend on specific instances and exist accessed statically. You lot tin add one as follows:

enum class Mean solar day {     MONDAY,     TUESDAY,     Midweek,     Thursday,     FRIDAY,     Sabbatum,     SUNDAY;      companion object {         fun getNumberOfDays() = values().size     } }        

At present, you can admission the getNumberOfDays() method this style:

Day.getNumberOfDays()        

As you lot can see, the method is called statically on the class and does non depend on any instance. Note that the synthetic static method values() was used while implementing information technology. Y'all are going to encounter what it is and how to use information technology very presently.

Using anonymous classes to define enum constants

We can create anonymous classes to define specific enum constants. In contrast to Java, Kotlin enum classes support bearding classes.

In particular, enum constants can exist instantiated by anonymous classes. They just take to give an implementation to the abstruse methods of the enum class itself. This can be achieved with the following syntax:

enum form Day {     Monday {         override fun nextDay() = TUESDAY     },     TUESDAY {         override fun nextDay() = WEDNESDAY     },     WEDNESDAY {         override fun nextDay() = THURSDAY     },     THURSDAY {         override fun nextDay() = FRIDAY     },     FRIDAY {         override fun nextDay() = SATURDAY     },     SATURDAY {         override fun nextDay() = Lord's day     },     Sunday {         override fun nextDay() = MONDAY     };      abstruse fun nextDay(): Twenty-four hour period }        

Equally shown here, each enum constant is instantiated by declaring its own anonymous classes while overriding the required abstract method. This is just as it would happen in any other Kotlin anonymous class.

Enums can implement interfaces

Although Kotlin enum classes cannot derive from a class, enum form, or an abstruse class, they tin actually implement one or more interfaces.

In this example, each enum abiding must provide an implementation of interface methods. This can be achieved with a common implementation, as follows:

interface IDay {     fun firstDay(): Day }   enum class Twenty-four hours: IDay {     MONDAY,     TUESDAY,     Midweek,     THURSDAY,     Fri,     SATURDAY,     SUNDAY;      override fun firstDay(): Day {       render MONDAY       }  }        

Or by using anonymous classes equally showed before:

interface IDay {     fun nextDay(): Day }   enum class Day: IDay {     MONDAY {         override fun nextDay() = TUESDAY     },     TUESDAY {         override fun nextDay() = WEDNESDAY     },     WEDNESDAY {         override fun nextDay() = Thursday     },     Thursday {         override fun nextDay() = Friday     },     Friday {         override fun nextDay() = Sat     },     SATURDAY {         override fun nextDay() = Lord's day     },     Dominicus {         override fun nextDay() = MONDAY     }; }        

In both cases, each enum abiding has the IDay interface method implemented.

Enums in action

At present that you have seen both bones and advanced features, you accept everything required to showtime using Kotlin enum classes. Let's see them in activeness through the three most mutual use cases.

Enums and when

Enum classes are especially useful when used with Kotlin's when provisional argument. This is because when expressions must take each possible condition into account. In other words, they must be exhaustive.

Since enums offer a limited ready of values by definition, Kotlin can utilise this to figure out if every condition was considered. If not, an error at compile fourth dimension will be thrown. Permit'south see enums in action with the when expression:

enum form Day {     MONDAY,     TUESDAY,     Midweek,     THURSDAY,     FRIDAY,     Sat,     SUNDAY }  fun main (currentDay: Solar day) {     when (currentDay) {         Twenty-four hours.Monday -> work()         Day.TUESDAY -> piece of work()         Twenty-four hours.WEDNESDAY -> piece of work()         Twenty-four hours.THURSDAY -> piece of work()         Day.Friday -> piece of work()         Day.Saturday -> rest()         Mean solar day.Sunday -> rest()     } }  fun work() {     println("Working") }  fun rest() {     println("Resting") }        

As just shown, enums let you lot to differentiate logic based on their value. They also make your code more readable and less error-decumbent. This is because they establish the maximum number of possible options to be considered in a when statement. This style, you cannot forget ane.

Enums and Kotlin synthetic methods

Similar to the aforementioned inbuilt properties, every enum class likewise has synthetic methods. They are automatically added by Kotlin at compile time and represent utility functions that can be accessed statically. Let'southward run across the most important ones and how to use them:

  • values()
    It returns the list of all the enum constants contained inside the enum class.
  • valueOf(value: String)
    It returns the enum abiding whose proper name property matches the value string passed equally a parameter. If not institute, an IllegalArgumentException is thrown.

Permit'southward see them in activeness through an instance:

enum form Mean solar day(val printableName: String) {     Monday("Monday"),     TUESDAY("Tuesday"),     WEDNESDAY("Midweek"),     THURSDAY("Thursday"),     FRIDAY("Friday"),     SATURDAY("Sat"),     SUNDAY("Sunday") }  fun main () {     for (day in Mean solar day.values())                 println(mean solar day.printableName)     println(Day.valueOf("Monday").printableName) }        

When run, the following effect would be printed:

Monday Tuesday Midweek Thursday Friday Saturday Dominicus Monday        

Note that the same result can be obtained past employing the 2 following Kotlin global functions: enumValues<T>() and enumValueOf<T>(). They allow y'all to admission any enum class T with a generic-based approach.

Iterating through enums

Finally, both use cases tin be combined to iterate through them thanks the values() synthetic method and execute unlike actions based on their value with a when expression. Let's look at an example based on this approach:

enum form Day(val printableName: String) {     MONDAY("Monday"),     TUESDAY("Tuesday"),     Midweek("Wednesday"),     THURSDAY("Thursday"),     Friday("Friday"),     SATURDAY("Saturday"),     SUNDAY("Sunday") }  fun principal () {     for (twenty-four hour period in Day.values()) {         // mutual behavior         println(day.printableName)          // action execute based on day value         when (day) {             Day.MONDAY -> work()             Day.TUESDAY -> work()             Day.WEDNESDAY -> piece of work()             Day.THURSDAY -> work()             Solar day.FRIDAY -> piece of work()             Solar day.SATURDAY -> residue()             Twenty-four hour period.Sunday -> residual()         }          // mutual behavior         println("---")     } }  fun work() {     println("Working") }  fun remainder() {     println("Resting") }        

This mode, custom logic can be executed based on each of the current possible values of which the enum class consists of. If launched, the snippet would render this:

Mon Working --- Tuesday Working --- Wednesday Working --- Thursday Working --- Friday Working --- Saturday Resting --- Sun Resting ---        

Conclusion

In this article, we looked at what Kotlin enum classes are, when and how to use them, and why. Equally shown, Kotlin enums come up with many features and offer y'all endless possibilities. So, simply thinking of them as a ready of constants would be a mistake, equally opposed to what happens in many other programming languages.

Since Kotlin enums are classes, they can have their own properties, methods, and implement interfaces. Plus, when used correctly, they tin can brand your lawmaking clearer, more readable, and less error-prone. This is why every Kotlin programmer should use them, and pedagogy everything required to practise it properly was what this article was about.

Thanks for reading! I hope that you found this article helpful. Feel gratis to attain out to me with any questions, comments, or suggestions.

LogRocket: Full visibility into your web apps

LogRocket Dashboard Free Trial Banner

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets yous replay the session to quickly empathise what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In improver to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the almost circuitous single-page and mobile apps.

Try information technology for free.

Read Enum Value From Argument in Java

Source: https://blog.logrocket.com/kotlin-enum-classes-complete-guide/

0 Response to "Read Enum Value From Argument in Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel