Scala进阶之路-Scala中的枚举用法案例展示
作者:尹正杰
版权声明:原创作品,谢绝转载!否则将追究法律责任。
Scala中的枚举值和Java中的枚举值有点差别,不过使用起来也都差大同小异,我这里分别写了一个Java定义枚举类型和Scala定义枚举类型的案例。
一.Java中定义枚举类型案例展示
1 /* 2 @author :yinzhengjie 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Scala%E8%BF%9B%E9%98%B6%E4%B9%8B%E8%B7%AF/ 4 EMAIL:y1053419035@qq.com 5 */ 6 package cn.org.yinzhengjie; 7 8 import java.util.Arrays; 9 10 /**11 * 定义枚举类型,只需要使用关键字enum关键字即可,内部的每个元素用逗号(",")分隔。12 */13 enum Day {14 MONDAY,15 TUESDAY,16 WEDNESDAY,17 THURSDAY,18 FRIDAY,19 SATURDAY,20 SUNDAY21 }22 23 24 public class EnumeratedTypeDemo {25 public static void main(String[] args) {26 //直接引用27 Day day = Day.MONDAY;28 System.out.printf("day:[%s]\n",day);29 30 /**31 * values()方法的作用就是获取枚举类中的所有变量,并作为数组返回32 */33 Day day1 = Day.valueOf("WEDNESDAY");34 System.out.printf("day1:[%s]\n",day1);35 36 /**37 * valueOf(String name)方法与Enum类中的valueOf方法的作用类似根据名称获取枚举变量,38 * 只不过编译器生成的valueOf方法更简洁些只需传递一个参数。39 */40 Day[] days = Day.values();41 System.out.printf("days:%s\n",Arrays.toString(days));42 //向上转型Enum43 Enum element = Day.FRIDAY;44 //获取class对象引用45 Class clasz = element.getDeclaringClass();46 if(clasz.isEnum()) {47 Day[] res = (Day[]) clasz.getEnumConstants();48 System.out.println("res:"+Arrays.toString(res));49 }50 }51 }52 53 54 55 56 57 /*58 以上代码执行结果如下:59 day:[MONDAY]60 day1:[WEDNESDAY]61 days:[MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY]62 res:[MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY]63 */
二.Scala中定义枚举类型案例展示
1 /* 2 @author :yinzhengjie 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Scala%E8%BF%9B%E9%98%B6%E4%B9%8B%E8%B7%AF/ 4 EMAIL:y1053419035@qq.com 5 */ 6 package cn.org.yinzhengjie 7 8 /** 9 * 定义枚举类型需要继承“Enumeration”这个抽象类10 */11 object ColorClassification extends Enumeration{12 val RED = Value(0,"红色")13 val YELLOW = Value(1,"黄色")14 val GREEN = Value(2,"绿色")15 val PINK = Value(3,"粉色")16 val BLUE = Value(4,"蓝色")17 val ORANGE = Value(5,"橙色")18 val BLACK = Value(6,"黑色")19 val WHITE = Value(7,"白色")20 }21 22 object EnumeratedType {23 def main(args: Array[String]): Unit = {24 println(ColorClassification.values)25 println(ColorClassification.RED)26 println(ColorClassification.RED.id)27 println(ColorClassification.ORANGE.id)28 }29 }30 31 32 33 34 /*35 以上代码执行结果如下:36 ColorClassification.ValueSet(红色, 黄色, 绿色, 粉色, 蓝色, 橙色, 黑色, 白色)37 红色38 039 540 */