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

47,034

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.

Share:
47,034

Related videos on Youtube

ruX
Author by

ruX

Focused on developer productivity and product delivery

Updated on March 02, 2022

Comments

  • ruX
    ruX about 2 years

    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.

  • Ilya Ryzhenkov
    Ilya Ryzhenkov about 9 years
    If you want it to be visible from Java as a static method, you need to annotate it with [platformStatic] as well.
  • Raphael
    Raphael about 7 years
    @JasperBlues Does for me, on Kotlin 1.1.1.
  • Kishan B
    Kishan B over 6 years
    Now you need to use @JvmStatic kotlinlang.org/docs/reference/…
  • HendraWD
    HendraWD over 6 years
    Use @JvmStatic if only you really want to use with Java, otherwise it's just waste of resources
  • jiahao
    jiahao about 6 years
    This is great. Just one more note: In order to access the static method, you need to add the keyword "Companion" between the class and the method, otherwise it won't work. Here is an example: jiahaoliuliu.com/2018/04/kotlin-static-method-at-enum.html
  • yole
    yole about 6 years
    The Companion reference is only needed if you're accessing the method from Java code, not from Kotlin.
  • Farid
    Farid over 4 years
    @yole to your last comment; IDE complains when used without companion reference even if it's Kotlin (version 1.3.50)
  • Leonardo Sibela
    Leonardo Sibela over 4 years
    I was trying to use a companion object, but the problem was that I forgot about the ; after declaring all the values from my enum. I think that using kotling made me pick up some bad habits lol
  • Siamak
    Siamak over 3 years
    @HendraWD Using @JvmStatic has almost no effect on resource.
  • HendraWD
    HendraWD over 3 years
    @Siamak SiaSoft @JvmStatic has effect. When you decompile the bytecode, you will see more codes added because of @JvmStatic
  • Siamak
    Siamak over 3 years
    @HendraWD I see but adding few lines of code for the sake of code simplicity and compatibility does not mean it's resource consuming. Indeed it's not free though :)
  • HendraWD
    HendraWD over 3 years
    @SiamakSiaSoft yes I agree, that's why I wrote: Use @JvmStatic if only you really want to use with Java