Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
169 views
Welcome To Ask or Share your Answers For Others

1 Answer

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]).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...