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")
      }
    }

  }

}

  

 

相关文章:

  • 2022-12-23
  • 2018-08-19
  • 2021-11-03
  • 2021-09-13
  • 2021-09-29
  • 2022-12-23
  • 2021-08-20
  • 2021-12-03
猜你喜欢
  • 2021-12-17
  • 2021-12-14
  • 2021-06-16
  • 2022-01-19
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案