Proxies / delegates in Scala

扶醉桌前 提交于 2019-11-28 04:34:31

Four questions, four answers

  1. I am, though family has to come first! Plus others are involved in looking at the general issue with synthesizing methods in a compiler plugin.

  2. If so, it will most likely be in a different form, perhaps without using annotations.

  3. I don't know of any equivalent plugins, although one of the Scala GSOC candidate projects was based partly on my autoproxy code. There is, however, one very clean solution that will work in most cases and doesn't need a compiler plugin at all: You define an implicit conversion from FooProxy to Foo that simply returns the self member; this will get you most of the way there. The main issues with the approach are that it'll make life harder if you need to use your code from Java, it may be less efficient in terms of speed/memory, and it's another imlicit that you have to be aware of.

  4. The frustrating part is that almost all of the necessary logic is already available in the compiler, and it's used for mixins, so there really should be an elegant way of handling the task.

Adam Warski recently blogged about a Macro-based approach that may work in Scala 2.11 and definitely works with the Macro Paradise compiler plugin in Scala 2.10.

This library would allow you to write

class FooProxy(@delegate wrapped: Foo) extends Foo {
    // added behavior
    def mymethod = ...

    // forwarding methods (generated for you)
    // def method1 = wrapped.method1
    // def method2(arg: String) = wrapped.method2(arg)
}

The project is in a very early, proof-of-concept, stage at the time of this writing, so caution is warranted.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!