在scal的伴生对象中,可以通过apply来实现类名加参数的方式来创建对象
object ApplyDemo {
def main(args: Array[String]): Unit = {
val list = List(1,2,3)
println(list)
val pig = new Pig("xiaohua")
// 使用apply来创建对象
val pig1 = Pig("小花")
val pig2 = Pig()
println("pig1.name=" + pig1.name) //heizhu
println("pig2.name=" + pig.name) // xiaohua
}
}
class Pig(pName:String){
var name:String = pName
}
object Pig{
// 编写一个apply
def apply(pName: String): Pig = new Pig(pName)
def apply(): Pig = new Pig("小黑")
}