scala 函數中嵌套函數
Scala中的合成功能 (Composition function in Scala)
Scala composition function is a way in which functions are composed in program i.e. mixing of more than one functions to extract some results. In Scala programming language, there are multiple ways to define the composition of a function. They are,
Scala組合函數是一種在程序中組合函數的方法,即混合多個函數以提取一些結果。 在Scala編程語言中,有多種方法來定義函數的組成。 他們是,
Using compose Keyword
使用撰寫關鍵字
Using andthen Keyword
使用然后關鍵詞
Passing method to method
傳遞方法
1)使用Compose關鍵字的Scala合成功能 (1) Scala composition function using Compose Keyword )
The compose keyword in Scala is valid for methods that are defined using "val" keyword.
Scala中的compose關鍵字對使用“ val”關鍵字定義的方法有效。
Syntax:
句法:
(method1 compose method2)(parameter)
Program:
程序:
object MyObject
{
def main(args: Array[String])
{
println("The percentage is "+(div compose mul)(435))
}
val mul=(a: Int)=> {
a * 100
}
val div=(a: Int) =>{
a / 500
}
}
Output
輸出量
The percentage is 87
2)使用andThe關鍵字的Scala合成函數 (2) Scala composition function using andThen Keyword)
Another composition keyword that works on function defined using val keyword function is andThen.
對使用val關鍵字function定義的函數起作用的另一個組合關鍵字是andThen 。
Syntax:
句法:
(method1 andThen method2)(parameter)
Program:
程序:
object myObject
{
def main(args: Array[String])
{
println("The percentage is "+(mul andThen div)(435))
}
val mul=(a: Int)=> {
a * 100
}
val div=(a: Int) =>{
a / 500
}
}
Output
輸出量
The percentage is 87
3)Scala合成函數的使用方法 (3) Scala composition function using method to method)
One more way to declaring composition function in Scala is passing a method as a parameter to another method.
在Scala中聲明復合函數的另一種方法是將一種方法作為參數傳遞給另一種方法。
Syntax:
句法:
function1(function2(parameter))
Program:
程序:
object myObject
{
def main(args: Array[String])
{
println("The percentage is "+ ( div(mul(456)) ))
}
val mul=(a: Int)=> {
a * 100
}
val div=(a: Int) =>{
a / 500
}
}
Output
輸出量
The percentage is 91
翻譯自: https://www.includehelp.com/scala/scala-composition-function.aspx
scala 函數中嵌套函數