首页 > 其他 > 详细

快学Scala 第九课 (伴生对象和枚举)

时间:2017-08-05 23:28:15      阅读:273      评论:0      收藏:0      [点我收藏+]

Scala没有静态方法和静态字段, 你可以用object这个语法结构来达到同样的目的。

对象的构造器只有在第一次被使用时才调用。

伴生对象apply方法:

类和它的伴生对象可以互相访问私有特性,他们必须存在于同一个源文件。

类中要访问类的伴生对象中成员,需要通过类.成员调用。

class Account private (val id: Int, initialBalance: Double){
  
}

object Account {
  def apply(initialBalance: Double)={
    new Account(1, initialBalance)
  }
}

object ObjectClassDemo {
  def main(args: Array[String]): Unit = {

    val a = Account(1)
    

  }
}

对象扩展类或特质:

object DoNothingAction extends UndoableAction("Do nothing"){
   override def undo(){
     
   }
   override def redo(){
     
   }
}

object ObjectClassDemo {
  def main(args: Array[String]): Unit = {
    val actions = Map ("open" -> ObjectClassDemo)
  }
}

应用程序对象:

object Hello extends App{
  println(args)
  
}

枚举:

继承Enumeration, 它是一个抽象类

object EnumColor extends Enumeration {

  type V = Value
  val Red = Value(1, "red")
  val Yellow = Value(2, "yellow")
  val Blue = Value(3, "blue")

  def main(args: Array[String]): Unit = {
    println(EnumColor.Red)
    println(EnumColor(2))
    println(EnumColor.withName("red"))
    import EnumColor.Value
    println(Red)

    for (c <- EnumColor.values) {
      c match {
        case EnumColor.Red    => println("get red")
        case EnumColor.Yellow => println("get yellow")
        case EnumColor.Blue   => println("get blue")
      }
    }

  }

}

  

 

快学Scala 第九课 (伴生对象和枚举)

原文:http://www.cnblogs.com/AK47Sonic/p/7291808.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!