我有一个方法fun
。它将函数文字作为参数并返回Int
。
def fun(arg: (Int) => Int): Int = {
val ret = 5 * arg + 10
ret
}
它代表一个函数f(x) = 5x+10
,它可以将参数作为另一个函数(例如g(x) = x+1)
,所以f(g(2)) = 5(2+1)+10 = 25
但我的Scala代码无法编译。为什么呢?
答案 0 :(得分:0)
Scala是一种函数式编程语言,它有一个非常好的功能,我们可以将函数作为参数传递,将它们存储在变量中,并从其他函数返回它们。
object FunctionCalc{
def f(Input: Int => Int) : Int ={
val temp = 10
(Input(5) + temp ) // It takes functions as input which take input as Int and return Int.
}
def f(Input:Int) :Int ={
Input + 4 //overloaded function
}
def g(arg : Int) :Int= {
arg+1 //adding 1
}
def h(arg:Int) : Int ={
arg+3 //adding 3
}
def main(args: Array[String]) {
println( f(g(2)))
println(f(h(4)))
println(f(6))
}
}
考虑上面的例子,我们将函数g和h作为f()的输入传递。
答案 1 :(得分:0)
因为您在代码中使用了函数“arg:Int => Int”作为参数。
“arg”是一个你可以像这样使用的功能。
def g(x:Int) = x+1
def f(arg:Int=>Int)(y:Int) = 5* arg(y) + 10
scala> f(g)(2)
res23: Int = 25