Scala singleton object

Article Directory


Overview: There is no static keyword in scala. If you want to define static variables and static methods similar to those in Java, you must use the singleton object in scala, that is, the Object
format:

object 单例对象名{
    
     }        //定义一个单例对象

Example: Define a variable and a method in the Dog singleton object

object demo1 {
    
    
  object Dog {
    
    
    val leg_num=4;
    def run(): Unit = println("狗跑起来了")
  }
  def main(args: Array[String]): Unit = {
    
    
    println(s"狗腿的数量:${Dog.leg_num}");
    Dog.run();
  }
}
}


Guess you like

Origin blog.csdn.net/zh2475855601/article/details/113868469