简体   繁体   中英

How do I use the trait scala.Proxy

我刚刚在API中找到了它并希望看到一两个例子以及解释它有什么用处。

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM