Ij Huij
Ij Huij

Reputation: 21

Passing a function with default parameter to a higher order function

This maybe a very basic question. I am new to Scala. In Scala, I have a function with a default parameter value for its second parameter:

def fun(number : Int, defaultNumber : Int = 0): Int = {number + defaultNumber}

I want to have a higherOrder function to which I can pass a lowerOrder function such as the function above whose second argument has a default value. First attempt is as follows:

def higherOrder(lowerOrder : (Int, Int) => Int, number: Int) =
        {lowerOrder(number)}

This obviously gives an error:

error: not enough arguments for method apply: (v1: Int, v2: Int)Int in trait Function2. Unspecified value parameter v2.

A way around this is to get the default value in the higherOrder function:

def higherOrder(lowerOrder : (Int, Int) => Int, number: Int, defaultNumber: Int = 0) =
        {lowerOrder(number, defaultNumber)}

But I don't want to do that because I may want to pass different lowerOrder functions that have different default values for their second parameter and I may not know what that default value is to pass the default value to the higherOrder function. Is there any solution for this?

Upvotes: 2

Views: 1083

Answers (1)

Rumesh Krishnan
Rumesh Krishnan

Reputation: 443

Define the trait for your lower Order function.

trait Fun {
    def apply(number : Int, defaultNumber : Int = 0): Int
}

Create lambda function for your lower Order function. Now you can use the function literal notation to define a Fun (note that you'll need to have started the REPL with -Xexperimental for this step to work)

val fun: Fun = { (number : Int, defaultNumber : Int) => number + defaultNumber }

Now, you can use this lambda function in your higher order function.

def higherOrder(lowerOrder : Fun, number: Int) =
        {lowerOrder(number)}

Call the higher order function now.

higherOrder(fun, 10)
> result: Int = 10

Upvotes: 2

Related Questions