Wrapping all of a class/object's functions

41 views
Skip to first unread message

Raymond Lau

unread,
May 13, 2015, 5:28:58 PM5/13/15
to scala...@googlegroups.com
So I'm writing a webservice that uses Redis as a cache.  However, I'd like for the Redis instance to not be completely necessary when I'm working in development mode, or if the cache goes down for some reason, the rest of my code keeps running.  Is there a way to wrap all the functions in a class/object (ex. the Redis scala client) so that if any of those functions are called and some condition is not met, I can add custom handling to every function?  

I'm thinking something like:

object MyWrapper extends RedisClient {

  def onAnyRedisClientFunctionCall(f : Any => Any) : Any = {
    redisClient match {
      case Some(client) => f
      case None => // log to error, return something else, etc.
    }
  }

}

Tim Harper

unread,
May 21, 2015, 11:42:55 AM5/21/15
to scala...@googlegroups.com
It seems you are looking to implement the delegator pattern.

The only way you'd get the level of magic for which you are looking is to write a Scala macro. The approach would be something along the lines of this:
  1. The macro would receive a reference to a class type definition
  2. The macro would introspect all public methods and create a new class definition, wrapping it as you specified
  3. An instance of the class generated by your macro would be returned
It's heavy stuff; A quick search came up with this: https://github.com/adamw/scala-macro-aop .  This is pretty close to what you want to do and you could learn from it.

I'm not sure I'd actually take the approach you're taking, I'd probably just wrap Redis, but it's not an entirely bad idea.
Reply all
Reply to author
Forward
0 new messages