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.
Related videos on Youtube
Comments
-
ruX about 2 years
Kotlin already have number of "static" methods for enum class, like
values
andvalueOf
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 about 9 yearsIf you want it to be visible from Java as a static method, you need to annotate it with [platformStatic] as well.
-
Raphael about 7 years@JasperBlues Does for me, on Kotlin 1.1.1.
-
Kishan B over 6 yearsNow you need to use @JvmStatic kotlinlang.org/docs/reference/…
-
HendraWD over 6 yearsUse
@JvmStatic
if only you really want to use with Java, otherwise it's just waste of resources -
jiahao about 6 yearsThis 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 about 6 yearsThe
Companion
reference is only needed if you're accessing the method from Java code, not from Kotlin. -
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 over 4 yearsI 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 over 3 years@HendraWD Using @JvmStatic has almost no effect on resource.
-
HendraWD over 3 years@Siamak SiaSoft
@JvmStatic
has effect. When you decompile the bytecode, you will see more codes added because of@JvmStatic
-
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 over 3 years@SiamakSiaSoft yes I agree, that's why I wrote: Use
@JvmStatic
if only you really want to use with Java