Mandroid
Mandroid

Reputation: 7484

Scala: how to access variables in a method defined in some other block of code

I have following code:

.hof((key, value) => {
    Some(..some processing result on key,value)
      .filterNot(_.isEmpty)
      .map(x: X => {....my code processing x using key,value with output y})
  }
)

I want to abstract out the function I passed to map into a method defined in class.

def myMethod(x: X) = {
   y = ....some computation....
   return y
}

But I need to have access to key,value in myMethod.

Is there a way to have that?

Upvotes: 0

Views: 189

Answers (2)

Tim
Tim

Reputation: 27356

You can define the method locally like this:

.hof((key, value) => {
  def myMethod(x: X) = {
   ???
  }

  Some(..some processing result on key,value)
    .filterNot(_.isEmpty)
    .map(myMethod)
  }
)

Otherwise you are going to have to pass (key, value) to the function as arguments.

(See answer from @slouc for tips on how to use currying to make this cleaner)

Upvotes: 2

slouc
slouc

Reputation: 9698

You can define myMethod in curried form:

def myMethod(key: Key, value: Value)(x: X) = {
  ... uses key and value ...
}

Then you can partially apply it in the map, passing it the key/value pair that you have at that point:

.map(myMethod(key, value))

Note that adding key/value pair to myMethod signature isn't some kind of "cheating"; if the method needs to use key and value, then it should have them passed as parameters.

This is the great thing about FP; once every function declares all the parameters it operates on, you can compose them easily.

Of course, you could simply place myMethod somewhere within the scope where key and value are going to be accessible (=closure), but by declaring them as parameters you are more flexible and you can place the method anywhere you want.

Upvotes: 3

Related Questions