apply使得创建实例时无需new.采用该机制,创建对象就等同于调用apply方法~
object Person {
def apply(name: String, age: Integer, favColor: String): Person = new Person(name, age, favColor)
}
class Person(name: String, age: Integer, favColor: String) {
def run(): Unit ={
println(s"$name is running")
}
}
object Test extends App{
//不需要new关键字,传给Person的参数等价于传给了aplly方法
val p=Person("xiaohong",23,"red")
p.run()//xiaohong is running
}
为了理解,我们加上new关键字,此时调用的是Person的构造方法,而不是apply方法
object Person {
def apply(name: String, age: Integer, favColor: String): Person = new Person(name, age, favColor)
}
class Person(name: String, age: Integer, favColor: String) {
def run(): Unit ={
println(s"$name is running")
}
}
object Test extends App{
//此时调用的是Person的构造方法,而不是apply方法
val p=new Person("xiaohong",23,"red")
p.run()//xiaohong is running
}
apply方法也可以显示调用,一般不这么做,这里是为了演示原理
object Person {
def apply(name: String, age: Integer, favColor: String): Person = new Person(name, age, favColor)
}
class Person(name: String, age: Integer, favColor: String) {
def run(): Unit ={
println(s"$name is running")
}
}
object Test extends App{
//显式调用apply
val p=Person.apply("xiaohong",23,"red")
p.run()//xiaohong is running
}
删掉apply方法,不用new创建对象会报错
让我们把class加上case关键字,此时不报错了. 说明系统自动创建了一个参的apply方法!!这是关键. 就是说如果是case class,系统会自动在其伴生对象中创建apply方法!
object Person {
}
case class Person(name: String, age: Integer, favColor: String) {
def run(): Unit ={
println(s"$name is running")
}
}
object Test extends App{
val p=Person("xiaohong",23,"red")
p.run()//xiaohong is running
}
apply在源码中的应用
比如创建Array
object ArrayDemo extends App{
val a=Array(1,2,5)
}
def apply(x: Int, xs: Int*): Array[Int] = {
val array = new Array[Int](xs.length + 1)
array(0) = x
var i = 1
for (x <- xs.iterator) { array(i) = x; i += 1 }
array
}
object ArrayDemo extends App{
val a=scala.collection.immutable.List(1,2,5)
}
override def apply[A](xs: A*): List[A] = xs.toList
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。