I just found it in the API and would like to see one or two examples along with an explanation what it is good for.
问题:
回答1:
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.
回答2:
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
}