兩個函數組裝爲一個函數,compose和andThen相反數組
def f(test: String):String = { "f(" + test + ")" } def g(test: String):String = { "g(" + test + ")" } val composeFunction = f _ compose g _ println("compose result:%s".format(composeFunction("compose"))) val andThenResult= f _ andThen g _ println("andThen result:%s".format(andThenResult("compose")))
執行結果函數
compose result:f(g(compose)) andThen result:g(f(compose))
對給定的輸入參數類型,偏函數只能接受該類型的某些特定的值。一個定義爲(Int) => String 的偏函數可能不能接受全部Int值爲輸入。
isDefinedAt 是PartialFunction的一個方法,用來肯定PartialFunction是否能接受一個給定的參數。code
val one: PartialFunction[Int, String] = { case 1 => "one" } println(one.isDefinedAt(1)) println(one.isDefinedAt(2)) val two: PartialFunction[Int, String] = { case 2 => "two" } val three: PartialFunction[Int, String] = { case 3 => "three" } val wildcard: PartialFunction[Int, String] = { case _ => "something else" } //PartialFunctions可使用orElse組成新的函數, //獲得的PartialFunction反映了是否對給定參數進行了定義。 val partial = one orElse two orElse three orElse wildcard println(partial(1)) println(partial(4))
執行結果:orm
true false one something else