apply方法
当明确了一个类或对象的主要用途时,可以用apply方法 很好用
class ApplyTest { def apply(){ print("dfd") } } object Test{ def main(args: Array[String]): Unit = { val a = new ApplyTest() print(a()) } }
单例对象可以和类具有相同的名称,此时该对象也被称为“伴生对象”。我们通常将伴生对象作为工厂使用,伴生对象和该类必须在同一个源文件当中,记得是源文件哦!
下面是一个简单的例子,可以不需要使用new
来创建一个实例了。
class ApplyTest { print("df") } object ApplyTest{ def apply() = new ApplyTest() }
在 Scala 中,我们经常谈论对象的函数式编程。这是什么意思?到底什么是函数呢?函数是一些特质的集合。具体来说,具有一个参数的函数是 Function1 特质的一个实例。这个特征定义了 apply()语法糖,让你调用一个对象时就像你在调用一个函数,函数本质上是类的实例
object AddT extends (Int=>Int){ def apply(m:Int):Int= m+1 } package com.test object Test{ def main(args: Array[String]): Unit = { AddT(1) } } class Add extends Function1[Int,Int]{ def apply(m:Int):Int=m+1 } object Test{ def main(args: Array[String]): Unit = { val a = new Add() a(1) } }
可以使用更直观快捷的 extends (Int => Int)
代替 extends Function1[Int, Int]
模糊匹配机制:
匹配类型 def simpleMatch(arg:Any)=arg match { case v:Int =>print("this is an Int") case v:(Int,String)=>print("this is int and string") case _=>print("afa") } 匹配成员 def calcType(calc: Calculator) = calc match { case _ if calc.brand == "hp" && calc.model == "20B" => "financial" case _ if calc.brand == "hp" && calc.model == "48G" => "scientific" case _ if calc.brand == "hp" && calc.model == "30B" => "business" case _ => "unknown"}
在最后一行指令中的_是一个通配符;它保证了我们可以处理所有的情况。
样本类
样本类也可以拥有普通的方法,样本类是被用来设计到模糊匹配中的
val hp20b = Calculator("hp", "20b") val hp20b = Calculator("hp", "20B") val hp30b = Calculator("hp", "30B") def calcType(calc: Calculator) = calc match { case Calculator("hp", "20B") => "financial" case Calculator("hp", "48G") => "scientific" case Calculator("hp", "30B") => "business" case Calculator(ourBrand, ourModel) => "Calculator: %s %s is of unknown type".format(ourBrand, ourModel) }
异常:
try { remoteCalculatorService.add(1, 2) } catch { case e: ServerIsDownException => log.error(e, "the remote calculator service is unavailable. should have kept your trusty HP.") } finally { remoteCalculatorService.close() } 也可以 val result: Int = try { remoteCalculatorService.add(1, 2) } catch { case e: ServerIsDownException => { log.error(e, "the remote calculator service is unavailable. should have kept your trusty HP.") 0 } } finally { remoteCalculatorService.close() }