apply方法編程
當明確了一個類或對象的主要用途時,能夠用apply方法 很好用app
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()語法糖,讓你調用一個對象時就像你在調用一個函數,函數本質上是類的實例this
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]
spa
模糊匹配機制:
scala
匹配類型 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"}
在最後一行指令中的_是一個通配符;它保證了咱們能夠處理全部的狀況。設計
樣本類code
樣本類也能夠擁有普通的方法,樣本類是被用來設計到模糊匹配中的orm
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() }