Scala中伴生类与伴生对象

Scala中伴生类与伴生对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.anthony

/**
* @ Description:
* @ Date: Created in 10:09 10/07/2018
* @ Author: Anthony_Duan
*/
object apply_test {

def main(args: Array[String]): Unit = {

// for(i <- 1 to 10){
// ApplyTest.incr
// }
// println(ApplyTest.count) // 10 object 本身就是个单例对象

val a = ApplyTest() //==>调用的是Object apply
println("----------------------------------")

val b = new ApplyTest()
println(b) //com.anthony.ApplyTest@7e0ea639
b() //this is class ApplyTest apply
a() //this is class ApplyTest apply

//类名()==> Object.apply
//对象名() ==> Class.apply

}


}


class ApplyTest{ //伴生类

def apply()={
println("this is class ApplyTest apply")
}


}

object ApplyTest{ //伴生对象

println("object ApplyTest enter")
var count = 0

def incr = count+=1

//最佳实践,在Object 的apply方法中new Class
def apply()= {
println("this is object ApplyTest apply")
new ApplyTest()
}

println("object ApplyTest leave")

}
-------------End Of This ArticleThank You For Reading-------------