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.
2 Answers
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.

- 20,967
- 7
- 70
- 108
-
1The currently active version of that plugin is autoproxy-lite: https://github.com/kevinwright/Autoproxy-Lite – Kevin Wright Apr 21 '11 at 09:33
-
Any ideas on how to best solve this today with scala 2.11, 2.12, and 2.13? – Alessandro Vermeulen Aug 25 '18 at 04:44
-
The `pimp-my-library` link is broken now. – Grzegorz Oledzki Dec 11 '18 at 14:06
-
1@GrzegorzOledzki I updated the link, redirecting it to a 2006 blog post on the topic by Martin Odersky. – Aaron Novstrup Dec 12 '18 at 19:36
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
}

- 90,905
- 62
- 285
- 365