首先说明apple的用法
当定义一个类,但是没有采用new 类时就是默认调用了apply 如:
class ApplyTest(val name:String ) {
println("right you are good :" + name)
}
object ApplyTest{
def main(args: Array[String]): Unit = {
val applyTest = new ApplyTest("Tom ");
val applyTest2 = ApplyTest("Jim")
}
def apply(key: String): String = {
println("come on :"+ key)
"you are here"
}
}
apply 必须定义在object 对象里面。
如果没有new 则会自动调用apply 方法
输出结果如下:
right you are good :Tom
come on :Jim
Process finished with exit code 0
比如 val x= List("d","v","a")
这个就是调用了Apply方法,List定义的源代码如下:
override def apply[A](xs: A*): List[A] = xs.toList
因为List是一个抽象的,被sealed 定义的所以只有Apply这个唯一的通道。不能new 不能继承,不是实现。(参考 scala 随笔(5) sealed 解析)
回到最开始的问题,如果在new 对象的时候有异常怎么办。代码如下:
class ApplyTest2 {
class ApplyTest(val name:String ) {
if(name.endsWith("jim")){
throw new Exception("you should enter a name end with jim")
}
println("right you are good :" + name)
}
object ApplyTest{
def main(args: Array[String]): Unit = {
val applyTest = new ApplyTest("Tom ");
val applyTest2 = ApplyTest("Jim")
val x = List("A","b")
}
def apply(key: String): String = {
println("come on :"+ key)
"you are here"
}
}
}
因为抛出一个异常,放入apple里面。然后可以进行一步动作。比如换种方式再new 一次
class ApplyTest2(val name :String) {
if(!name.endsWith("jim")){
throw new Exception("you should enter a name end with jim")
}
println("right you are good :" + name)
}
object ApplyTest2{
def main(args: Array[String]): Unit = {
val applyTest2 = ApplyTest2("tom")
}
def apply(key: String) = {
try{
new ApplyTest2(key)
}catch {
case e: Exception
=> "you are wrong " + e.printStackTrace()
case _:Any
=> "you are wrong too"
}
}
}