Peter Bratton
Peter Bratton

Reputation: 6408

How to write a non-trivial function that returns a function in Scala?

In Javascript, I would write a higher order function returning another function this way:

var f = function(x) {
  return function(y) {
    // something using x and y
  }
}

The Scala syntax for this seems to be:

def f(x: Any)(y: Any) = // Something with x and y

which is fine if you never need to do anything before creating the returned function. But suppose you had to process x somehow before creating the return function (example again in Javascript):

var f = function(x) {
  // Something using x
  return function(y) {
    // something using y based on the above logic
  }
}

The documentation is unclear on this point.

Upvotes: 0

Views: 139

Answers (3)

ccheneson
ccheneson

Reputation: 49410

As @Chirlo said, Int => Int denotes a function .

A => B is just syntactic sugar for the trait FunctionN[A,B] where

  • A is the input type
  • B the output type
  • FunctionN varies according to the number of inputs : Function1 accepts 1 input, Function2 accepts 2 inputs...

So using Chirlo's example,

def hof(i:Int) = {
    // do some other stuff....

   (x:Int) => i + x  //the last statement, so this function will be returned. 
 }

, this is equivalent to

def hof = new Function1[Int,Function1[Int,Int]] {   
    def apply(i:Int) = new Function1[Int,Int] {     
        def apply(x:Int) = i + x 
    }
}

Upvotes: 1

Lee
Lee

Reputation: 144176

You can expliclty return a function instead of using separate parameter lists e.g.

def f(x: Any) = {
    //something using x
    (y: Any) => //something with x and y
}

or

val f: (Any => (Any => Any)) = x => {
    //something using x
    y => //something with x and y
}

Upvotes: 1

Chirlo
Chirlo

Reputation: 6132

For example, calling the following function:

def hof(i:Int) = (x:Int) => x + i

returns a Int => Int function, that is one that will take an Int and return an Int. For your case you can do like:

 def hof(i:Int) = {
    // do some other stuff....

   (x:Int) => i + x  //the last statement, so this function will be returned. 
 }

Upvotes: 5

Related Questions