且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用特征scala.Proxy

更新时间:2023-09-13 23:48:22

Proxy trait为创建提供了有用的依据代表,但请注意,它仅提供任何等于 hashCode中的方法的实现 toString )。您必须自己实现任何其他转发方法。 Proxy通常与 pimp-my-library模式一起使用:

The Proxy trait provides a useful basis for creating delegates, but note that it only provides implementations of the methods in Any (equals, hashCode, and toString). You will have to implement any additional forwarding methods yourself. Proxy is often used with the pimp-my-library pattern:

class RichFoo(val self: Foo) extends Proxy {
   def newMethod = "do something cool"
}

object RichFoo {
   def apply(foo: Foo) = new RichFoo(foo)
   implicit def foo2richFoo(foo: Foo): RichFoo = RichFoo(foo)
   implicit def richFoo2foo(richFoo: RichFoo): Foo = richFoo.self
}

标准库还包含一组可用于创建收集代理的特征( SeqProxy SetProxy MapProxy 等)。

The standard library also contains a set of traits that are useful for creating collection proxies (SeqProxy, SetProxy, MapProxy, etc).

最后,scala-incubator中有一个编译器插件( AutoProxy插件)。另请参见此问题

Finally, there is a compiler plugin in the scala-incubator (the AutoProxy plugin) that will automatically implement forwarding methods. See also this question.