0

I'm working on a project in scala, and was wondering if there is some way I could define some set of methods that would all have the same code, for instance, all functions that start with the letter c. For instance:

class A {
    a() {..}
    b() {..}
    c[a-z]+() {...}
}
var a = new A();
a.click();
a.cook()

In this example, click() and cook() would both call the c[A-Z]+ method

Would it be possible to create such functionality or is it outside Scala's capabilities?

Alternatively, is there some way to allow all possible method calls on an object, and have a sort of "default" method

class B {
    a() {..}
    b() {..}
    default() {...}
}
var b = new B();
b.somethingelse();

where somethingelse() would actually call default() but still have access to the somethingelse() method name.

Chance R.
  • 68
  • 8
  • 4
    You could take a look at [Dynamic][1] to see if it helps. [1]: http://stackoverflow.com/questions/15799811/how-does-type-dynamic-work-and-how-to-use-it – Eduardo Dec 03 '14 at 00:57
  • This is definitely awesome and can kind of work for my situation, but the only problem is that I was hoping to be able to call random methods in a child class, and have the parent class handle them. Dynamic seems to work for instances of a class, but not great if you are just working with subclassing – Chance R. Dec 03 '14 at 02:47

1 Answers1

1

I don't think you can achieve what you are asking by calling things directly on the class.

But there is a solution, albeit one that includes some clutter-code: you could have a parametrized wrapper:

class Wrapper[T](val instance: T) {
  def call(methodName:String, params: Any*) = ???
}

Now you can instantiate it with your class:

val wrapper = Wrapper[A](new A())
wrapper.call("click")

So what does "call" do? it extracts through reflection all the methods of the instance, and then do whatever you think is more meaningful (call a default one, call all the matching ones, something else).

val methodNames = instance.getClass.getMethods.map(_.getName)

The downside is that you have to call wrapper.call instead of the method, the upside is that you have a lot more control of what to do with the method. If you choose this approach, consider also that you may not need to compute the method list all the times unless you allow the wrapper's inner instance to change. Also, check that the parameters passed are of the right type and number!

Diego Martinoia
  • 4,592
  • 1
  • 17
  • 36