How do I use the trait scala.Proxy
Asked Answered
A

2

12

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.

Apery answered 10/10, 2010 at 15:7 Comment(0)
A
14

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.

Antonantone answered 10/10, 2010 at 16:38 Comment(4)
The currently active version of that plugin is autoproxy-lite: github.com/kevinwright/Autoproxy-LiteSowens
Any ideas on how to best solve this today with scala 2.11, 2.12, and 2.13?Fowler
The pimp-my-library link is broken now.Terrorism
@GrzegorzOledzki I updated the link, redirecting it to a 2006 blog post on the topic by Martin Odersky.Antonantone
Q
3

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
}
Queeniequeenly answered 10/10, 2010 at 15:18 Comment(1)
So this is basically machinery for creating delegates?Apery

© 2022 - 2024 — McMap. All rights reserved.