shakedzy shakedzy -4 years ago 153
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 = {
def p2(s: String): String = {
def p3(s: String): String = {

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
, which will pass the result as the argument for
and do on. Is there a simple way to do that?


What I have so far:

At the moment I have a hard-coded sequence:

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

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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download