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枚舉類的所有信息。
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中的枚舉類的一些要點。
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作為參數來獲取枚舉常量。 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函數的函數,該函數將對枚舉常量進行迭代以檢查是否有任何匹配字符串并返回布爾值的函數。
Every enum constant has properties: name
, ordinal
to retrieve the name and position of the constant.
每個枚舉常量都具有以下屬性: name
, ordinal
以檢索常量的名稱和位置。
fun main(args: Array<String>) {println(Months.January.name) //prints Januaryprintln(Months.March.ordinal) // prints 2for (enum in Months.values()) {println(enum.name)}
}
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 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.
}
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
每個枚舉常量都必須重寫
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
不能從枚舉常量中調用。
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枚舉
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态