Dynamic Proxy using Scalas new Dynamic Type

627 views Asked by At

Is it possible to create an AOP like interceptor using Scalas new Dynamic Type feature? For example: Would it be possible to create a generic stopwatch interceptor that could be mixed in with arbitrary types to profile my code? Or would I still have to use AspectJ?

3

There are 3 answers

0
Alex Cruise On BEST ANSWER

I'm pretty sure Dynamic is only used when the object you're selecting on doesn't already have what you're selecting:

From the nightly scaladoc:

Instances x of this trait allow calls x.meth(args) for arbitrary method names meth and argument lists args. If a call is not natively supported by x, it is rewritten to x.invokeDynamic("meth", args)

Note that since the documentation was written, the method has been renamed applyDynamic.

0
Adam Rabung On

I think your odds are bad. Scala will call applyDynamic only if there is no static match on the method call:

class Slow {
  def doStuff = //slow stuff
}
var slow = new Slow with DynamicTimer
slow.doStuff

In the example above, scalac won't call applyDynamic because it statically resolved your call to doStuff. It will only fall through to applyDynamic if the method you are calling matches none of the names of methods on the type.

0
Kevin Wright On

No.

In order for a dynamic object to be supplied as a parameter, it'll need to have the expected type - which means inheriting from the class you want to proxy, or from the appropriate superclass / interface.

As soon as you do this, it'll have the relevant methods statically provided, so applyDynamic would never be considered.