The most basic usage of enumeration class is to implement a type safe enumeration .

Enumeration constants are separated by commas , Each enumeration constant is an object .

enum class Color{

Enumeration initialization

Every enumeration is an instance of an enumeration class , They can be initialized :

enum class Color(val rgb: Int) {

The default name is the enumeration character name , Value from 0 Start . If you need to specify a value , You can use its constructor :

enum class Shape(value:Int){

Enumeration also supports to declare its own anonymous classes and corresponding methods 、 And the method of covering the base class . Such as :

enum class ProtocolState {
override fun signal() = TALKING
override fun signal() = WAITING
}; abstract fun signal(): ProtocolState

If the enumeration class defines any members , To use a semicolon to separate enumeration constant definitions in a member definition

Use enumeration constants

Kotlin Enumeration classes in have composition methods , Allow traversal of defined enumeration constants , And get the enumeration constant by its name .

EnumClass.valueOf(value: String): EnumClass // Conversion specifies name For enumeration value , If the match is not successful , Will throw out IllegalArgumentException
EnumClass.values(): Array<EnumClass> // In the form of an array , Return enumeration value

Get information about enumeration :

val name: String // Get enumeration name 
val ordinal: Int // Gets the order in which enumeration values are defined in all enumeration arrays


enum class Color{
} fun main(args: Array<String>) {
var color:Color=Color.BLUE println(Color.values())
println(color.ordinal) }

since Kotlin 1.1 rise , have access to  enumValues<T>()  and  enumValueOf<T>()  Functions access constants in enumeration classes in a generic way :

enum class RGB { RED, GREEN, BLUE }
inline fun <reified T : Enum<T>> printAllValues() {
print(enumValues<T>().joinToString { })
} fun main(args: Array<String>) {
printAllValues<RGB>() // Output RED, GREEN, BLUE

Kotlin More articles on enumerating classes

  1. Kotlin—— Intermediate ( 5、 ... and ): Enumeration class (Enum)、 Interface class (Interface) Detailed explanation

    In the previous chapter , Detailed classes (class) An example is given , I mentioned classes (class) Instantiation . Constructors . Statement . Realization way . and Java The difference between classes, etc . But for Kotlin The use of classes in is much more than that . And mentioned above ...

  2. Kotlin Data class and seal class

    Data class Kotlin You can create a data only class , Keyword is  data: data class User(val name: String, val age: Int) The compiler will automatically choose from the main constructor according to ...

  3. Linq Improve coding efficiency —— Third articles Enumeration classes you need to know

      as everyone knows , If a class can be enumerated , So this class has to implement IEnumerable Interface , And just what we have linq It's all an inheritance from IEnumerable Anonymous class of interface , So here's the problem ,IEnumerable Make ...

  4. 0029 Java Learning notes - object-oriented - Enumeration class

    You can create several objects ? n Multiple : Most classes , You can create objects at will , As long as the memory doesn't explode 1 individual : For example, singleton class A limited number of : Adopt the design idea of singleton class , Only a few specific objects can be created : And then there are enumeration classes . Create a few objects , ...

  5. FastJson Convert custom enumeration class

    There are states in a project that require enumeration types , What's stored in the database is name( english ), And what the front desk needs to show is text( chinese ). So you need to implement the sequence yourself . Such as object : import java.util.Date; im ...

  6. Java Enumeration class

    If you want to define an enumeration class : public enum Size { SAMLL, MEDIUM, LARGE, EXTRA, EXTRA_LARGE}; actually , The type defined by this declaration is a class , It happens to have 4 An example ...

  7. SpringMVC Methods that automatically encapsulate enumeration classes

    springmvc Enumeration classes cannot be automatically encapsulated by default , The solution is as follows : 1. Enumeration class public enum GoodsPromoteEnum { /** * 0 The high-quality goods */ fine(" The high-quality goods ", ...

  8. Enumeration class valueOf The question of method

    Enumeration class valueOf Method has only one parameter and Enum There are two parameters in the class , Excuse me, Enum In the instance class valueOf Where does the method come from ?   answer :jvm Added when compiling .

  9. java Enumeration in (enum) Small example . I've learned enumeration before, but it doesn't work , Here's an enumeration class to help you understand ( It's very superficial )

    Enumerating classes directly , The code is easy to understand . package; /** * * @author shengzhou ...

Random recommendation

  1. Ant Introduce

    Today I'd like to introduce Ant,Ant Is based on Java Cross platform building tools for , It's easy to use , And it's scalable . Upgradeable . It can be used for small personal projects , It can also be used for large . Multiple groups of collaborative software projects . In our project development , To build a software product , I ...

  2. php And The data access

    The data access : Mode one : Deprecated , Just to understand 1. Make a connection ( Establish a channel ) $db=mysql_connect("localhost","root","123& ...

  3. Section 69 ,css Fundamentals of entry

    css Fundamentals of entry Learning points : 1. Use CSS 2. Three ways 3. Cascade and inherit This chapter mainly discusses HTML5 in CSS ( Cascading style sheets ), It's for HTML The presentation of document appearance is typesetting and formatting . One Use CSS CSS ...

  4. 9.2、Libgdx Input processing mouse 、 Touch and keyboard

    ( Official website Libgdx The main devices supported are desktop Or browser mouse support ,Android Touch screen support and keyboard support . Let's take a look at . keyboard The user presses or releases a key to generate ...

  5. Log4Net Configuration log

    1.log4net 1) Create a new one Net Blank items , Click management in the reference NuGet Package , Search for log4net And install 2) establish log4net.config The configuration file stay configuration Add the following code , ...

  6. server time zone

    Question why Because of the Mysql Database driver version too high , There are time zone differences between database and system , So there's a problem . Problem solving Spring Boot In the configuration file url: jdbc:mysql:// ...

  7. JS Data types and data analysis

    The stack area :(stack)- Release is automatically allocated by the compiler , Stores the parameter values of the function , The value of a local variable, etc . It is characterized by small storage volume , High frequency data . It's analogous to memory . Heap area :(heap)- Release is usually assigned by the programmer , If the developer doesn't release , At the end of the program ...

  8. Baptize the soul , Practice python(51)-- Reptile — Chameleon camouflage

    The chameleon principle The chameleon must be known to all , They change their colors according to the situation around them , Disguise yourself . So does a reptile have this skill ? Of course there are , Don't worry about it . From the last one , Have you ever thought about it , From the perspective of website management , ...

  9. C# clone

    Cloning is a way that must be used in prototyping patterns , It will return an object that is consistent with the current object data . As its name suggests , It's like carving out of a mold . There are two types of cloning : Shallow clone . A deep clone . 1. Shallow clone Shallow cloning is the simplest . The most direct way . Just the class ...

  10. In the second week of leetcode

    4/4 It's been a busy week , One day is compiling , One day is doing pattern recognition homework ,( Brush Warcraft skin one day ), I played for two days on the weekend , On the whole, it's still lax , I only did it for about two days leetcode, It's painted 10 Problem , Shame, shame . Decide to attach the code to this summary each time ...