首先我们知道在scala中class是类,object是对象,如果class和object同名则称呼对方为伴生对象或伴生类,比如我们写一个people类
class people(id : Int, name : String){
def say = "hello :"+ name + ",my id is :"+id
}
object people{
def apply(id : Int, name : String) = {
println("is apply")
new people(id, name)
}
}
object test{
def main(args : Array[String]){
val p = people(2, "tom")
p say
}
}
在这段代码中,我并没有new people,这是为什么呢?因为这是伴生对象的一个好处,因为创建伴生对象是不需要new关键词的,而我们people(2, "tom")实际是调用了其中的apply方法,这是scala中的一个语法糖,这样的设计让代码更加精简。
原文:http://my.oschina.net/ssrs2202/blog/495085