【发布时间】:2014-12-28 23:57:23
【问题描述】:
下面的工作表代码定义了两个函数。
fun 接受 Int => Int 类型的函数参数并调用函数
参数值为 2
funParam 接受一个 Int 参数并返回此参数 + 3。
这是一个人为的例子,以便直观地了解函数是如何传递的 写函数式代码的时候。
object question {
println("Welcome to the Scala worksheet") //> Welcome to the Scala worksheet
def fun(f : Int => Int) = {
f(2)
} //> fun: (f: Int => Int)Int
def funParam(param : Int) : Int = {
param + 3
} //> funParam: (param: Int)Int
fun(funParam) //> res0: Int = 5
}
为什么我不能使用类似的东西:fun(funParam(3))
这会导致编译器错误:type mismatch; found : Int required: Int => Int
这是否意味着我不能调用函数“fun”,将变量传递给 funParam ? 这就是我尝试使用 fun(funParam(3)) 实现的目标,也许有办法实现这一目标?
【问题讨论】:
-
@Marth 我期待“funParam(3)”作为函数传递给“fun”,但似乎我不完全理解函数是如何评估的
标签: scala