Enumeration class

Enumeration classes in Kotlin are very similar to enumeration types in Java and have the properties of classes. An enumerable set of values of the same type is typically defined as an enumerated class.

Basic usage

In Kotlin, enumeration types exist in the form of classes and are therefore called enumeration classes. Examples are as follows:

enum class Color {
    RED, GREEN, BLUE
}
Copy the code

Everything in Kotlin is an object, so every enumerated type is an object, separated by a comma.

Here’s how to use it:

Var color: color = color. BLUE var color2 = color. GREEN // Compare two enumerated variables var bool: Boolean = color == color2Copy the code

Note that a reference to a value in an enumerated class requires the name of the enumerated class. By default, the element value of the enumeration class is printed directly, and the name of the element value is printed.

Specifies a numeric value for an enumerated value

Each value of the enumeration class is the object of the current enumeration class, so if you want to specify a number for the value of each enumeration class, you just pass it in through the constructor.

enum class Direction private constructor(var value: Int) {
    NORTH(1), WEST(2), EAST(3), SOUTH(4)
}
Copy the code

Other features

First, specify a value for each enumeration value. This number does not necessarily start at 0 or be in order, so the position of the enumeration value in the enumeration class may not be the same as the value corresponding to the enumeration value.

Both Java and Kotlin provide apis to get the names and indexes of enumerated values. Kotlin provides the name and ordinal attributes to get the enumeration value name and index, respectively.

Println (color.name) // Returns the name of the enumeration println(color.ordinal) // returns the index of the enumerationCopy the code

In addition, you can use the valueOf method to pass in the enumeration value name to get the value corresponding to the enumeration value.

extension

Extensions are a very important feature in Kotlin, where you can add members to a class without source code. In the case of team development, functional modules can also be spread out to multiple people through extension.

Extending native APIS

Although the JDK and Kotlin native provide rich apis, these apis still seem inadequate, and additional apis need to be added to these libraries.

You extend your system’s classes outside of the class, and by putting the extended parts into your own source code, the source code can still run on other machines’ JDK and Kotlin runtimes. Kotlin can extend both the JDK API and Kotlin.

fun ArrayList<Int>.swap(index1: Int, index2: Int) {
    val tmp = this[index1]
    this[index1] = this[index2]
    this[index2] = tmp
}
Copy the code

The above code extends the native collection class ArrayList by extending the swap method.

This code can be placed in any Kotlin file, usually at the top of the Kotlin file, or, of course, before calling swap.

Extend custom classes

The purpose of the extension class is many, in addition to the system class needs to be extended, we write our own class also need to be extended, extension custom class method and extension system class the same:

open class Parent(var value1: Int, var value2: Int) {
    var mVaule1 = value1
    var mValue2 = value2
    fun add(): Int {
        return mVaule1 + mValue2
    }
}

class Child(value1: Int, value2: Int) : Parent(value1, value2) {
    fun sub(): Int {
        returnValue1-value2}} // Add an output result method fun Parent to the Parent class by extension.printlnResult() {
    println("${value1}+${value2}=${add()}")
}

fun Child.printlnResult() {
    println("${value1}-${value2}=${sub()}")}Copy the code

Because open Boone is used in top-level functions, it is not possible to add inheritable member functions through extension (Kotlin does not allow inheritance by default).

Resolution of member function conflicts

If a member function added to a class by extension has exactly the same structure as the original member function in the class, which one takes precedence?

The answer is: internal member functions take precedence, so they cannot be overridden by extension methods.

Extended attributes

Just like the extension method, the Kotlin property must be initialized in a class, which requires the backing field. You can either store the property’s value in the field or obtain the property’s value from the field. However, there is no backing field for an extended property, so the extended property needs to implement the setter section in order to initialize it.

class MClass {
    var mValue: Int = 0
    var str: String = ""
        get() = str
        set(value) {field = value}} // Attribute extension var McLass. newVaule: Int get() = mValueset(value) {
        mValue = value
    }
Copy the code

Because the extended property property does not have a backing field, saving and retrieving the property value requires a class member variable. However, the member variable must be declared public, otherwise the extended attribute cannot be accessed.

Extended adjoint object

Companion objects: Resolves the embarrassment of having no static members in the Kotlin class.

If you have right adjoint objects in your class, you can use extensions to add members to adjoint objects.

class MClas {
    companion object {

    }
}

fun MClas.Companion.func() {
    println("Adjoint object member function")}Copy the code

Extended range

The extension code written above is all in the same kotlin file of the same package. Of course, it is the same in different Kotlin files of the same package, but if it is in different kotlin files of the package, you need to use import to import the corresponding resources. Import packages were introduced earlier, so they are no longer cumbersome.

Extensions in a class

Extensions can also be defined in a class.

class D {
    fun bar() {
        println("D.bar")
    }
}

class C {
    fun baz() {
        println("C.baz"} // Add a method extension fun D to another class in a class.foo() {
        bar()
        baz()
    }

    fun caller(d: D) {
        d.foo()
    }
}
Copy the code

Call a member function of a particular class

If you extend A in B, is it A call to A’s or B’s member functions that both A and B have in A’s extension methods? As follows:

class A {
    fun func() {
        println("A.func")
    }
}

class B {
    fun func() {
        println("B.func")
    }

    fun A.doo() {func() // call func method [email protected]() // call func method of class B} fun call(A: A) {a.doo()}}Copy the code

If you call B’s func function from a. doo, you need to use [email protected](), whereas calling A method from class A can be used directly.

Extend the inheritance of members

It was mentioned earlier that extended members cannot be inherited, but this statement is not accurate. It is more accurate to say that extension members at the top level of the unload cannot be inherited because the open keyword modifier cannot be added. But you can add the open keyword to another class extension within a class.

summary

Although enumerated classes don’t come up very often in your code, they are a good way to define a set of related values that can be enumerated, or at least make your code more readable (far better than using constants or numbers directly). While extensions are supported in many languages, taking full advantage of the Kotlin extension makes your code easier to maintain and provides greater flexibility.

More exciting content, welcome to pay attention to my wechat public number – Android motor vehicle