十一、Scala 伴生类和伴生对象,Apply
一、伴生类和伴生对象
object ApplyApp {
}
class ApplyTest{
}
object ApplyTest{
}
class ApplyTest
是 object ApplyTest
伴生类object ApplyTest
是 class ApplyTest
伴生对象
二、初探 Apply
object ApplyApp {
def main(args: Array[String]): Unit = {
for (i <- 1 to 10){
ApplyTest.incr // 直接调用ApplyTest,就是Object对象
}
println(ApplyTest.count) // 结果10,说明object 就是一个单例对象
}
}
class ApplyTest{
}
object ApplyTest{
println("Object ApplyTest enter...")
var count = 0
def incr = {
count = count + 1
}
println("Object ApplyTest leave...")
}
输出
Object ApplyTest enter...
Object ApplyTest leave...
10
三、Apply 最佳实践
直接可以调用的就是对象:val b = ApplyTest() // ==> Object.apply
需要new,就是类: val c = new ApplyTest
object ApplyApp {
def main(args: Array[String]): Unit = {
// 直接调用的是 Object.apply,这里不需要再new了,因为在Object里面的apply已经new 了
val b = ApplyTest() // ==> Object.apply
println("--------------------------------------")
val c = new ApplyTest
println(c)
c()
}
}
class ApplyTest{
def apply() = {
println("class ApplyTest apply...")
}
}
object ApplyTest{
println("Object ApplyTest enter...")
var count = 0
def incr = {
count = count + 1
}
// 最佳实践:在Object的apply方法中去 new Class
def apply() = {
println("Object ApplyTest apply...")
// 在object中的Apply中new class
new ApplyTest
}
println("Object ApplyTest leave...")
}
输出
Object ApplyTest enter...
Object ApplyTest leave...
Object ApplyTest apply...
--------------------------------------
com.hhcycj.scala.object_04.ApplyTest@735b5592
class ApplyTest apply...