How can I create "static" method for enum in Kotlin?

EnumsStaticKotlin

Enums Problem Overview


Kotlin already have number of "static" methods for enum class, like values and valueOf

For example I have enum

public enum class CircleType {
    FIRST
    SECOND
    THIRD
}

How can I add static method such as random(): CircleType? Extension functions seems not for this case.

Enums Solutions


Solution 1 - Enums

Just like with any other class, you can define a class object in an enum class:

enum class CircleType {
  FIRST,
  SECOND,
  THIRD;
  companion object {
     fun random(): CircleType = FIRST // http://dilbert.com/strip/2001-10-25
  }
}

Then you'll be able to call this function as CircleType.random().

EDIT: Note the commas between the enum constant entries, and the closing semicolon before the companion object. Both are now mandatory.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionruXView Question on Stackoverflow
Solution 1 - EnumsyoleView Answer on Stackoverflow