Article Directory
Overview: apply the method used to create the object, free new operation, make the code more simple and elegant
format:
object 伴生对象名{
def apply(参数列表) = new 类名(参数列表)
}
Example:
- Define a Person class, which contains two fields: name and age
- Define the apply method in the companion object to realize the free new operation of creating the Person object
- Create an object of this class in the main method, and print the name and age
object demo {
object Person{
def apply(name:String,age:Int): Person = new Person(name:String,age:Int)
}
def main(args: Array[String]): Unit = {
var person=Person("张荷",20);
println(person);
}
}