Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

scala - Invoking function which accept functions as parameters

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...