Parag
Parag

Reputation: 79

Pass member function as parameter in scala

I am trying to implement several functions which will take two objects of same type [A], a threshold, call a member function of the type [A] on both objects, compare the results with the threshold to return a boolean.

As a concrete example, say, [A] has several member functions which return ints. I would prefer to create a factory of functions which take such a member function, fn, two objects, a and b, of type [A], and a threshold, thresholdFn, and returns a function whose body is (a.fn + b.fn > thresholdFn). Is it possible to create a factory fn like:

def myFn(
    a: MyObject,
    b: MyObject,
    getter: <<<MyObject getter function>>>,
    int threshold): Boolean = {
  def myFn1(...) {
  (<<< a.getter + b.getter >>>)  > threshold
  }
  myFn1
}

[A] is an external Java class.

Upvotes: 0

Views: 1106

Answers (1)

senia
senia

Reputation: 38045

You can't do it in exactly this way. You could create a function and use it like this: getter(a).

def myFn(a: MyObject, b: MyObject, getter: MyObject => Int, int threshold): Boolean = {
  (getter(a) + getter(b))  > threshold
}

Usage:

myFn(a, b, _.fn, threshold)

If you want to abstract over type of a and b you should move getter to additional parameters group:

def myFn[T](a: T, b: T, int threshold)(getter: T => Int): Boolean = {
  (getter(a) + getter(b))  > threshold
}

myFn(a, b, threshold){ _.fn }

Upvotes: 2

Related Questions