官术网_书友最值得收藏!

Enum classes

Enumeration is a specific type of class; a variable of a given enum type is limited to a set of predefined constants—those that have been defined by the type. To define an enumeration, you could use enum class keywords, as in the following example where we create a type for all the days in a week:

    enum class Day {  MONDAY, TUESDAY, WEDNESDAY, THURSDAY,  FRIDAY, SATURDAY, SUNDAY} 

Enumeration, like all classes, can take a constructor parameter. We can define an enum class to represent the planets in our solar system, and for each planet we retain the total mass and radius:

    public enum class Planet(val mass: Double, val radius: Double) { 
      MERCURY(3.303e+23, 2.4397e6), VENUS(4.869e+24, 6.0518e6),  EARTH(5.976e+24, 6.37814e6), MARS(6.421e+23, 3.3972e6),  JUPITER(1.9e+27, 7.1492e7), SATURN(5.688e+26, 6.0268e7),  URANUS(8.686e+25, 2.5559e7), NEPTUNE(1.024e+26, 2.4746e7); 
    } 

I made the two val parameters so they are exposed as properties. All enumeration instances come with two properties predefined. One is name of the String type, and the second one is ordinal of the int type. The former returns the name of the instance, and the latter gives you the position in the enumeration's type declaration.

Similar to Java, Kotlin provides you with helper methods to work with enumeration classes. To retrieve an enum value based on the name, you will need to use the following:

    Planet.valueOf("JUPITER") 

To get all the values defined, you will need to write the following:

    Planet.values()

Just like any class, enumeration types can inherit an interface and implement it anonymously for each enum value. Here is an example of how you could achieve this:

    interface Printable { 
      fun print(): Unit 
    } 
 
    public enum class Word : Printable { 
      HELLO { 
        override fun print() { 
          println("Word is HELLO") 
        } 
      }, 
      BYE { 
        override fun print() { 
          println("Word is BYE") 
        } 
      } 
    } 
 
    val w= Word.HELLO 
    w.print() 
主站蜘蛛池模板: 二连浩特市| 辰溪县| 理塘县| 从化市| 防城港市| 甘洛县| 东阿县| 龙江县| 霍林郭勒市| 琼中| 普定县| 新干县| 秦皇岛市| 阿瓦提县| 新邵县| 静乐县| 石狮市| 三亚市| 曲水县| 墨江| 长泰县| 阿拉尔市| 禄劝| 台中县| 滨海县| 峡江县| 白城市| 绍兴市| 嵊州市| 新沂市| 广饶县| 乐山市| 菏泽市| 余姚市| 屯留县| 家居| 兴化市| 英吉沙县| 罗平县| 汝州市| 文成县|