scala高阶函数之枚举类

 

枚举类: 不同于java, 有自己的定义规则 

object demo_meiju {
    def main(args: Array[String]): Unit = {
        def crossrod(light:Tractlight.Value): Unit = {
            light match {
                case Tractlight.RED => println("行车不规范,亲人丙行泪")
                case Tractlight.YELLOW => println("请等一等")
                case Tractlight.GREE => println("请通行")
                case _ => println("翻车了")
            }
        }
        crossrod(Tractlight.RED)
    }

    /*
      scala中定义枚举的方法, 继承枚举的父类
     */
    object Tractlight extends Enumeration{
        val RED, YELLOW, GREE = Value
    }
}

 

 

用样例类同样能实现枚举类

object demo_meiju_temp {
    // 密封类
    sealed abstract class Tracklight(color: String)
    // 用样例类模拟过马路, 继承父类, 三个子类
    case class RED(red:String) extends Tracklight(red)
    case class GREEN(gre:String) extends Tracklight(gre)
    case class YELLOW(yel:String) extends Tracklight(yel)


    def main(args: Array[String]): Unit = {
        crossroad(RED("红灯"))
    }
    // 参数为样例类的父类
    def crossroad(light:Tracklight): Unit ={
        light match {
            case RED(red) => println(red)
            case GREEN(gre) => println(gre)
            case YELLOW(yel) => println(yel)
        }
    }

}

 

posted on 2021-08-31 14:24  孔扎根  阅读(290)  评论(0编辑  收藏  举报

导航