107

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.

1 Answer 1

248

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.

Sign up to request clarification or add additional context in comments.

13 Comments

If you want it to be visible from Java as a static method, you need to annotate it with [platformStatic] as well.
Now you need to use @JvmStatic kotlinlang.org/docs/reference/…
Use @JvmStatic if only you really want to use with Java, otherwise it's just waste of resources
The Companion reference is only needed if you're accessing the method from Java code, not from Kotlin.
@SiamakSiaSoft yes I agree, that's why I wrote: Use @JvmStatic if only you really want to use with Java
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.