shakedzy shakedzy - 3 months ago 7
Scala Question

Scala: execute functions one by one and passing parameters between them

I have a class with an unknown number of functions:

class processors {
def p1(s: String): String = {
//code
}
def p2(s: String): String = {
//code
}
def p3(s: String): String = {
//code
}
...
}


I want to be able to run all the function one by one in the order they are written (p1 -> p2 -> p3 -> ...). Also, I would like to pass the initial string to
p1
, which will pass the result as the argument for
p2
and do on. Is there a simple way to do that?

EDIT:

What I have so far:

At the moment I have a hard-coded sequence:

val processors = Seq(p1 _, p2 _, p3 _).reduce(_ andThen _)
processors(some_string)


I'd like to avoid the hard-coding, basically..

Answer

Reflection can help here. this example is for single param integer argument, but it can be extended to multiple arguments but it gets bit tricky dealing with types. Argument types can be queried from the class.

class A {
  def f(x: Int): Int = 2 * x
  def g(x: Int): Int = x * x
}

val clazz = classOf[A]

clazz.getDeclaredMethods.filter(! _.getName.contains("$"))
.map(x => {a: Integer => x.invoke(new A(), a: Integer).asInstanceOf[Integer] })
.reduce(_ andThen _)(new Integer(1))

For your case just replace Int with String

To maintain the order of execution of the functions in the class

try to put number in the function name and then order them by parsing string obtained from getName method