kotlin枚举_Kotlin枚举班

kotlin枚举

In this tutorial, we’ll be looking into Kotlin Enum classes. What’s in store for them? How are they different from enums in Java? We’ll be discussing everything you need to know about kotlin enum class at length.

在本教程中,我们将研究Kotlin Enum类。 他们要买什么? 它们与Java枚举有何不同? 我们将详细讨论您需要了解的有关Kotlin枚举类的所有信息。

Kotlin枚举班 (Kotlin Enum Class)

Enumerations in Kotlin are data types that hold a set of constants. Enums are defined by adding the modifier enum in front of a class as shown below. Yes, in Kotlin, Enums are classes.

Kotlin中的枚举是保存一组常量的数据类型。 枚举是通过将改性剂定义enum在前面 ,如下所示。 是的,在Kotlin中, 枚举是class

enum class Months{
    January,
    February,
    March
}

Here are some important points about enum classes in kotlin.

以下是有关Kotlin中的枚举类的一些要点。

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

    每个枚举常量都是一个对象。 枚举常量用逗号分隔。
  • Each of the enum constants acts as separate instances of the class.

    每个枚举常量都充当该类的单独实例。
  • Enums are useful in enhancing the readability of your code since it assigns pre-defined names to constants.

    枚举对增强代码的可读性很有用,因为它为常量分配了预定义的名称。
  • Unlike classes, an instance of enum classes cannot be created using constructors.

    与类不同,不能使用构造函数创建枚举类的实例。
  • Hence, we can assert that enum classes are abstract.

    因此,我们可以断言枚举类是抽象的。

Let’s see how the enum class is initialized in the main function of our class.

让我们看看如何在类的main函数中初始化enum类。

fun main(args: Array<String>) {

    println(Months.January) //prints January
    println(Months.values().size) //prints 3
    println(Months.valueOf("March")) //prints March

    for (enum in Months.values()) {
        println(enum.name)
    }

    println(Months.valueOf("Mar")) //throws java.lang.IllegalArgumentException: No enum constant Months.Mar
}

Few inferences from the above code:

上面的代码很少有推断:

  • values() returns the enum constants in the form of an array over which we can iterate to retrieve each enum constant.

    values()以数组的形式返回枚举常量,我们可以在该数组上进行迭代以检索每个枚举常量。
  • valueOf() is used to fetch an enum constant using a String as the argument.

    valueOf()用于使用String作为参数来获取枚举常量。
  • If the value doesn’t match with any of the constants, a runtime exception would be thrown.

    如果该值与任何常量都不匹配,则将引发运行时异常。
  • Let’s see how to tackle this scenario.

    让我们看看如何解决这种情况。

fun enumContains(name: String): Boolean {
    return enumValues<Months>().any { it.name == name }
}

fun main(args: Array<String>) {

    if (enumContains("")) {
        println(Months.valueOf(""))
    } else {
        println("The string value does not match with any of the enum constants.") //this gets printed.
    }

}

enumContains is a function that calls the lambda function any which iterates over the enum constants to check if any of them matches the string and returns a boolean.

enumContains是一个调用lambda函数的函数,该函数将对枚举常量进行迭代以检查是否有任何匹配字符串并返回布尔值的函数。

枚举属性 (Enum Properties)

Every enum constant has properties: name, ordinal to retrieve the name and position of the constant.

每个枚举常量都具有以下属性: nameordinal以检索常量的名称和位置。

fun main(args: Array<String>) {
    
    println(Months.January.name) //prints January
    println(Months.March.ordinal) // prints 2
    for (enum in Months.values()) {
        println(enum.name)
    }
}

枚举toString() (Enum toString())

We can override the toString() function in the enum class as shown below.

我们可以在枚举类中重写toString()函数,如下所示。

enum class Months {
    January,
    February,
    March;

    override fun toString(): String {
        return super.toString().toUpperCase()
    }
}

fun main(args: Array<String>) {
    println(Months.January) //prints JANUARY
    println(Months.January.name) //prints January
     println(Months.valueOf("March")) //prints MARCH
}

Enums are classes. So besides defining the constants we can define other things as well that can be present in a class. To do so we need to first end the enum part with a semi colon.
Note: Month.January invokes the toString() method of the class whereas Month.January.name directly prints the enum constant’s name.

枚举是类。 因此,除了定义常量之外,我们还可以定义类中可以存在的其他内容。 为此,我们需要首先以半冒号结束枚举部分。
注意Month.January调用类的toString()方法,而Month.January.name直接打印枚举常量的名称。

枚举初始化 (Enum Initialisation)

Enum constants can be initialized using primary constructors as shown below.

枚举常量可以使用主要构造函数进行初始化,如下所示。

enum class Months(var shorthand: String) {
    January("JAN"),
    February("FEB"),
    March("MAR");
}

fun main(args: Array<String>) {

    var x = Months.January
    println(x.shorthand) //prints JAN
    x.shorthand = "Shorthand changed to J."
    println(Months.January.shorthand) //prints Shorthand changed to J.
}

枚举作为匿名类 (Enums as Anonymous classes)

Enum constants can behave as anonymous classes be implementing their own functions along with overriding base functions from the class as shown below.

枚举常量的行为就像匿名类正在实现其自身的功能以及从该类覆盖基本函数一样,如下所示。

enum class Months(var shorthand: String) {
    January("JAN"){
        override fun printSomething() {
            println("First month of the year.")
        }
    },
    February("FEB"){
        override fun printSomething() {
            println("Second month of the year.")
        }
    },
    March("MAR"){
        override fun printSomething() {
            println("Third month of the year.")
        }
    };
    var a: String = "Hello, Kotlin Enums"
    abstract fun printSomething()
}

fun main(args: Array<String>) {
    Months.February.printSomething() //prints Second month of the year.
    println(Months.February.a) //prints Hello, Kotlin Enums
}

Each of the enum constants must override

每个枚举常量都必须重写

枚举内的枚举 (Enum inside an Enum)

It’s possible to define another enum class in the current enum class as shown below.

可以在当前枚举类中定义另一个枚举类,如下所示。

enum class Months {
    January,
    February,
    March;

    enum class Day{
        Monday,
        Tuesday,
        Wednesday
    }
}

fun main(args: Array<String>) {
    println(Months.Day.Tuesday) //prints Tuesday
}

Only an enum class can invoke another one. The inner class Day cannot be invoked from the enum constants.

只有一个枚举类可以调用另一个。 内部类Day不能从枚举常量中调用。

枚举以及何时 (Enums and when)

when is Kotlin equivalent of switch in Java. We’ve covered the workings of it in the Control Flow tutorial.
An example showing how when statements are used with enums is given below.

when Kotlin相当于Java中的switch。 我们已经在“ 控制流”教程中介绍了它的工作原理。
下面给出一个示例,说明如何将语句与枚举一起使用。

enum class Months {
    January,
    February,
    March;
}

fun main(args: Array<String>) {

    var m = Months.February

    when (m) {
        Months.January  -> print("Matches with Jan")
        Months.February -> print("Matches with Feb") //prints this.
        Months.March -> print("Matches with Mar")
    }
}

This brings an end to kotlin enum tutorial.

Kotlin枚举教程到此结束。

References: Kotlin Docs

参考: Kotlin Docs

翻译自: https://www.journaldev.com/18688/kotlin-enum-class

kotlin枚举

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值