How do I use the trait scala.Proxy

走远了吗. 提交于 2019-11-30 18:24:34

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
}

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

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

It looks like you'd use it when you need Haskell's newtype like functionality.

For example, the following Haskell code:

newtype Natural = MakeNatural Integer
                  deriving (Eq, Show)

may roughly correspond to following Scala code:

case class Natural(value: Int) extends Proxy {
  def self = value
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!