object Test {
def main(args: Array[String]): Unit = {
//Object Student就是一个单例
println(Student.score)
//Student() 不是new出来的,会去调用apply方法
val student = Student()
student.study()
}
}
class Student{
def apply():Unit = {
println("class Student apply")
}
def study():Unit = {
println("study hard")
}
}
object Student{
def score:Int = 100
def apply():Student = {
println("[enter] object student apply")
new Student
}
}
结果:
100
[enter] object student apply
study hard
笔记:
伴生对象加括号,会直接调用伴生对象里面的 apply 方法
实践:
Spark 源码中,有大量的这种使用