kotlin構造函數,kotlin枚舉_Kotlin枚舉班

 2023-11-19 阅读 26 评论 0

摘要: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. 在本教程中,我們將研究K

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 Januaryprintln(Months.values().size) //prints 3println(Months.valueOf("March")) //prints Marchfor (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 Januaryprintln(Months.March.ordinal) // prints 2for (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 JANUARYprintln(Months.January.name) //prints Januaryprintln(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.Januaryprintln(x.shorthand) //prints JANx.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.Februarywhen (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枚舉

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/4/182974.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息