Enum class kotlin get

Enum-классы

Наиболее базовый пример использования enum (перечисления) — это реализация типобезопасных перечислений.

Каждая enum-константа является объектом. При объявлении константы разделяются запятыми.

Так как константы являются экземплярами enum-класса, они могут быть инициализированы.

enum class Color(val rgb: Int)

Анонимные классы

Enum-константы также могут объявлять свои собственные анонимные классы как с их собственными методами, так и с перегруженными методами базового класса.

enum class ProtocolState < WAITING < override fun signal() = TALKING >, TALKING < override fun signal() = WAITING >; abstract fun signal(): ProtocolState > 

Следует заметить, что при объявлении в enum-классе каких-либо членов, необходимо отделять их от объявления констант точкой с запятой.

Реализация интерфейсов в классах enum

Enum-класс может реализовывать интерфейс (но не наследоваться от класса), предоставляя либо единственную реализацию членов интерфейса для всех элементов enum, либо отдельные для каждого элемента в своем анонимном классе. Это достигается путем добавления интерфейсов, которые вы хотите реализовать, к объявлению класса enum следующим образом:

import java.util.function.BinaryOperator import java.util.function.IntBinaryOperator enum class IntArithmetics : BinaryOperator, IntBinaryOperator < PLUS < override fun apply(t: Int, u: Int): Int = t + u >, TIMES < override fun apply(t: Int, u: Int): Int = t * u >; override fun applyAsInt(t: Int, u: Int) = apply(t, u) > fun main() < val a = 13 val b = 31 for (f in IntArithmetics.values()) < println("$f($a, $b) = $") > > 

Работа с enum-константами

Enum-классы в Kotlin имеют синтетические методы для вывода списка объявленных enum-констант и для получения enum-константы по её имени. Ниже приведены сигнатуры этих методов (при условии, что имя enum-класса — EnumClass ):

EnumClass.valueOf(value: String): EnumClass EnumClass.values(): Array

Метод valueOf() выбрасывает исключение IllegalArgumentException , если указанное имя не соответствует ни одной enum-константе, объявленной в классе.

()` and `enumValueOf ()` functions: —>

К константам в enum-классе можно получить доступ универсальным способом, используя функции enumValues() и enumValueOf() :

enum class RGB < RED, GREEN, BLUE >inline fun > printAllValues() < print(enumValues().joinToString < it.name >) > printAllValues() // выведет RED, GREEN, BLUE 

Каждая enum-константа имеет поля, в которых содержатся её имя и порядковый номер в объявлении enum-класса.

val name: String val ordinal: Int 

Также enum-константы реализуют интерфейс Comparable. Порядок сортировки соответствует порядку объявления.

Источник

Enum

The common base class of all enum classes. See the Kotlin language documentation for more information on enum classes.

Constructors

The common base class of all enum classes. See the Kotlin language documentation for more information on enum classes.

Properties

name

Returns the name of this enum constant, exactly as declared in its enum declaration.

ordinal

Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero).

Functions

clone

Throws an exception since enum constants cannot be cloned. This method prevents enum classes from inheriting from Cloneable .

compareTo

Compares this object with the specified object for order. Returns zero if this object is equal to the specified other object, a negative number if it’s less than other, or a positive number if it’s greater than other.

equals

Indicates whether some other object is «equal to» this one. Implementations must fulfil the following requirements:

hashCode

Returns a hash code value for the object. The general contract of hashCode is:

toString

Returns a string representation of the object.

Extension Properties

declaringJavaClass

Returns a Java Class instance of the enum the given constant belongs to.

Extension Functions

coerceAtLeast

Ensures that this value is not less than the specified minimumValue.

coerceAtMost

Ensures that this value is not greater than the specified maximumValue.

coerceIn

Ensures that this value lies in the specified range minimumValue..maximumValue.

Ensures that this value lies in the specified range.

compareTo

Compares this object with the specified object for order. Returns zero if this object is equal to the specified other object, a negative number if it’s less than other, or a positive number if it’s greater than other.

rangeTo

Creates a range from this Comparable value to the specified that value.

rangeUntil

Creates an open-ended range from this Comparable value to the specified that value.

Inheritors

AnnotationRetention

Contains the list of possible annotation’s retentions.

AnnotationTarget

Contains the list of code elements which are the possible annotation targets

CharCategory

Represents the character general category in the Unicode specification.

CharDirectionality

Represents the Unicode directionality of a character. Character directionality is used to calculate the visual ordering of text.

CopyActionResult

The result of the copyAction function passed to Path.copyToRecursively that specifies further actions when copying an entry.

CpuArchitecture

Central Processor Unit architecture.

DeprecationLevel

Possible levels of a deprecation. The level specifies how the deprecated element usages are reported in code.

DurationUnit

The list of possible time measurement units, in which a duration can be expressed.

FileWalkDirection

An enumeration to describe possible walk directions. There are two of them: beginning from parents, ending with children, and beginning from children, ending with parents. Both use depth-first search.

FutureState

State of the future object.

InvocationKind

Specifies how many times a function invokes its function parameter in place.

KVariance

Represents variance applied to a type parameter on the declaration site (declaration-site variance), or to a type in a projection (use-site variance).

KVisibility

Visibility is an aspect of a Kotlin declaration regulating where that declaration is accessible in the source code. Visibility can be changed with one of the following modifiers: public , protected , internal , private .

LazyThreadSafetyMode

Specifies how a Lazy instance synchronizes initialization among multiple threads.

Источник

Enum classes

The most basic use case for enum classes is the implementation of type-safe enums:

Each enum constant is an object. Enum constants are separated by commas.

Since each enum is an instance of the enum class, it can be initialized as:

Anonymous classes

Enum constants can declare their own anonymous classes with their corresponding methods, as well as with overriding base methods.

If the enum class defines any members, separate the constant definitions from the member definitions with a semicolon.

Implementing interfaces in enum classes

An enum class can implement an interface (but it cannot derive from a class), providing either a common implementation of interface members for all the entries, or separate implementations for each entry within its anonymous class. This is done by adding the interfaces you want to implement to the enum class declaration as follows:

import java.util.function.BinaryOperator import java.util.function.IntBinaryOperator //sampleStart enum class IntArithmetics : BinaryOperator, IntBinaryOperator < PLUS < override fun apply(t: Int, u: Int): Int = t + u >, TIMES < override fun apply(t: Int, u: Int): Int = t * u >; override fun applyAsInt(t: Int, u: Int) = apply(t, u) > //sampleEnd fun main() < val a = 13 val b = 31 for (f in IntArithmetics.values()) < println("$f($a, $b) = $«) > >

All enum classes implement the Comparable interface by default. Constants in the enum class are defined in the natural order. For more information, see Ordering.

Working with enum constants

Enum classes in Kotlin have synthetic methods for listing the defined enum constants and getting an enum constant by its name. The signatures of these methods are as follows (assuming the name of the enum class is EnumClass ):

Below is an example of these methods in action:

The valueOf() method throws an IllegalArgumentException if the specified name does not match any of the enum constants defined in the class.

You can access the constants in an enum class in a generic way using the enumValues() and enumValueOf() functions:

enum class RGB < RED, GREEN, BLUE >inline fun printAllValues() < print(enumValues().joinToString < it.name >) > printAllValues() // prints RED, GREEN, BLUE

For more information about inline functions and reified type parameters, see Inline functions.

In Kotlin 1.9.0, the entries property is introduced as a replacement for the values() function. The entries property returns a pre-allocated immutable list of your enum constants. This is particularly useful when you are working with collections and can help you avoid performance issues.

Every enum constant also has properties: name and ordinal , for obtaining its name and position (starting from 0) in the enum class declaration:

Источник

Читайте также:  Html clear img src
Оцените статью