Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 612
ruX Avatar asked Feb 26 '15 21:02

ruX


People also ask

Can enum have static methods?

The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared.

Can we create static methods in Kotlin?

Kotlin is a statically typed programming language for the JVM, Android and the browser, 100% interoperable with Java. Blog of JetBrains team discussing static constants in Kotlin.

Can enum class have methods Kotlin?

Since Kotlin enums are classes, they can have their own properties, methods, and implement interfaces.


1 Answers

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.

like image 88
yole Avatar answered Sep 23 '22 01:09

yole