Running a function from another module in Scala

Good morning,

I am trying to execute a particular function in a given module, with particular arguments in Scala.

The function I am running originally accepts three parameters, M - module name ; F - function name; A - arguments.

Is it possible to do something like :

Behaviors.receiveMessage {
case mon_start => apply(M, F, A)

And secondly, what type should the 3 parameters be please :slight_smile:

Thanks a lot and good day :slight_smile:

Hi.

Are you just asking how you to implement the apply function from above which should call a function qualified by its fully qualified class and method name given some arguments?

You would need to use reflection: Overview | Reflection | Scala Documentation

In order to call a method, you need to have an instance of the class/object at first, of course.

1 Like

Given your immediate question, cbley is right that reflection is the immediate and simplest implementation answer. However, there are many problem space contexts within which depending upon reflection is actually either a code smell or even an anti-pattern. For example, if you intend to deploy your results into many production server contexts (especially with high-security requirements) or outside the JVM (Scala.js, Scala Native, Spark, etc.), you will find reflection significantly impeding, if not outright blocking, your movement forward.

For example, just simply based on your stated requirements which imply concurrency and/or parallel computation, another better architecture and/or design option might be using Akka actors:
https://doc.akka.io/docs/akka/current/typed/guide/introduction.html

And finally, another architecture and/or design option is to deeply understand the problem space and exploit the many FP (Functional Programming) alternatives which offer almost all the benefits of reflection with none of the code smell nor anti-patterns.

4 Likes

Agreed. Are you coming from an Erlang background, by any chance? (The question sounds Erlang-ish.) If so, the Scala language is very, very different, but the Akka library is a descendant of Erlang, and will look a bit more familiar.

3 Likes

Thanks a lot all for your help :slight_smile: