【问题标题】:Invoking function which accept functions as parameters调用接受函数作为参数的函数
【发布时间】: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


【解决方案1】:

如果我理解正确,您可以使用:

val res = fun(_ => funParam(3))
println(res) // 6

您不能将Int 类型的值(调用funParam(3) 的结果)传递给fun 类型的参数Int => Int (Function1[-T1, +R])。

【讨论】:

  • 谢谢,你能解释一下通配符在这种情况下的用法吗?
  • 表示没有使用lambda参数或者没有意义。在这种情况下 2 来自您的 f(2) 调用。
【解决方案2】:

为什么我不能使用类似:fun(funParam(3)) 这会导致编译器 error : type mismatch; found : Int required: Int => Int

因为funParam(3) 的计算结果为Int 类型的,但fun 采用Int => Int 类型的函数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-09
    • 2021-03-29
    • 2014-08-23
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 2023-01-30
    • 1970-01-01
    相关资源
    最近更新 更多