compose&andThen
两个函数组装为一个函数,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))
PartialFunction
对给定的输入参数类型,偏函数只能接受该类型的某些特定的值。一个定义为(Int) => String 的偏函数可能不能接受所有Int值为输入。
isDefinedAt 是PartialFunction的一个方法,用来确定PartialFunction是否能接受一个给定的参数。
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))
执行结果:
true
false
one
something else