Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the trait scala.Proxy

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.

like image 320
Jens Schauder Avatar asked Oct 10 '10 15:10

Jens Schauder


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.

like image 118
Aaron Novstrup Avatar answered Nov 16 '22 11:11

Aaron Novstrup


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
}
like image 42
missingfaktor Avatar answered Nov 16 '22 12:11

missingfaktor