Class和object名称相同,object就是class的伴生对象,class就是object的伴生类
文章目录
Scala中没有static
Scala没有Java中的static 静态成员
替代品是 Scala中有:单例对象:Singleton object
除了用Object替换Class之外,单例对象定义看上去就像是类的定义,如下例子
object ObjectApp {
def main(args: Array[String]): Unit = {
print(Timer.currentCnt())
print(Timer.currentCnt())
print(Timer.currentCnt())
}
}
object Timer{
var cnt = 0;
def currentCnt():Int = {
cnt += 1
cnt
}
}
object Timer{
var cnt = 0;
def currentCnt():Int = {
cnt += 1
cnt
}
}
class Timer{
var cnt = 0;
def currentCnt():Int = {
cnt += 1
cnt
}
}
Object 类似是一个全局的
伴生对象为Timer 同名伴生类为Timer
单例对象会在第一次被访问的时候初始化。
Apply
object ObjectApp {
def main(args: Array[String]): Unit = {
// print(new Timer().currentCnt())
// print(new Timer().currentCnt())
// print(new Timer().currentCnt())
val test = new ApplyTest
println(test)
println(test.test())
}
}
object ApplyTest{
var cnt = 0
def inc={
cnt += 1
}
def test() = {
print("-------------Object test------------------")
}
print("---------------ApplyTest object leave------------")
}
class ApplyTest{
def test() = {
print("--------------ApplyTest class-------------------")
}
}
new 出来 走的是class
val b = ApplyTest() //名字() —> object.apply
val b = ApplyTest() //名字() ---> object.apply
println(b)
b.test()
object ApplyTest{
println("---------------ApplyTest object enter------------")
var cnt = 0
def apply() = {
println("--------------- object apply------------")
new ApplyTest //在object里面的apply方法里 去new一个对应的class
}
val c = new ApplyTest()
new class 出来 不会调用class里面的方法
class ApplyTest{
def test() = {
println("--------------ApplyTest class-------------------")
}
def apply() = {
"--------------- object apply------------"
}
}
println(c())
当打印C() 时就会走Class里面的apply方法
总结
Object Class 同名 伴生类 伴生对象
//***********************************************************
名字() -------> object apply // 一般情况下 在这个apply方法里面是new一个伴生类
对象() -------> class apply // 一般不用
//***********************************************************
应用
new Array[Int](4)
Array(1,2,3,4)
直接Array就会调用 apply方法