Invoking function which accept functions as parame

2019-09-20 15:22发布

问题:

Below worksheet code defines two functions. fun accepts a function parameter of type Int => Int and invokes the function with parameter value 2

funParam accepts an Int parameter and returns this parameter + 3.

This is a contrived example so as gain an intuition of how functions are passed around when writing functional code.

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

}

Why can't I use something like : fun(funParam(3)) This causes compiler error : type mismatch; found : Int required: Int => Int

Does this mean I cannot invoke function "fun" passing a variable into funParam ? This is what I attempt to achieve using fun(funParam(3)) , perhaps there is an way of achieving this ?

回答1:

If I understand you correctly you can use:

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

You can't pass a value of type Int (the result of calling funParam(3)) to fun which parameter is of type Int => Int (Function1[-T1, +R]).



回答2:

Why can't I use something like : fun(funParam(3)) This causes compiler error : type mismatch; found : Int required: Int => Int

because funParam(3) evaluates to a value of type Int but fun takes a function of type Int => Int



标签: scala