rss· 投稿· 设为首页· 加入收藏· 繁體版
当前位置: 火魔网 » 程序开发 » Scala

scala-chapter 3 : rounding out the essen

1. About the Scala EnumerationWhile enumerations are a built-in part of many programming languages, Scala takes a different route and implements them as a class in its standard library. This means there is no special syntax for enumerations in Scala, as in Java and C#. Instead, you just define an object that extends the Enumeration class. as it is quoted in the above text
  1. There is no built-in construct for enumeration in Scala language
  2. Scala enumeration is just an object
  3. the scala enumeration object extends from "Enumeration"
  4. There is no connection between Scala enumerations and the enum constructs in Java and C#.
2. Enumeration example I, longer form// code-examples/Rounding/enumeration-script.scalapackage ch03object Breed extends Enumeration {
  // 1. Value is a method, take a string argument. This method assign a long-form breed name to each enumeration value
  val doberman = Value("Doberman Pinscher")
  val yorkie = Value("Yorkshire Terrier")
  val scottie = Value("Scottish Terrier")
  val dane = Value("Great Dane")
  val portie = Value("Portuguese Water Dog")
}object EnumerationScript {
   
    // 2. Unit is the void in Scala
    def main(args : Array[String]) : Unit = {
        // 3. each enumeration has a unique id
        // 4. Enumeration.values get value collection
        for (breed <- Breed.values)  println(breed.id + "\t" + breed)
        Breed.values.filter(_.toString.endsWith("Terrier")).foreach(println)
    } 3. Enumeration example II, longer form
// code-examples/Rounding/enumeration-script.scala
package ch03object WeekDay extends Enumeration {
  // 1. type alias
  type WeekDay = Value
  // 2. scala enumeratio are just normal object, use vals to indicated different "enumeration" values
  val Mon, Tue, Wed, Thu, Fri, Sat, Sun = Value
}object DaysEnumerationScript {
  // 3. import all enumerations, incluing the type alias
  import WeekDay._
  def isWorkingDay (d : WeekDay) = ! (d == Sat || d == Sun)     
  def main(args : Array[String]) : Unit = {
   
    WeekDay.values filter isWorkingDay foreach println   
  }
顶一下
(0)
踩一下
(0)