« Return to Thread: Private names

Re: Private names

by Rafael de F. Ferreira-2 :: Rate this Message:

Reply (Restricted by the Administrator) | Reply to Author | View in Thread

Hi Janne.

I was under the impression that the
ad-hoc-initialization-block-using-anonymous-subclass trick was the
"standard way" to do this kind of thing in Scala. In your example, I
infer that Message is a Java class, but if it was written in Scala,
one idiom for initialization would be to declare abstract vals, like
this:

abstract class Message {
  val displayName:String
  val content:String
}

sw sendMessage (new Message {
   val displayName = somename
   val content = format("Hello, %s! %s!", displayName, somecontent)
})


Anyway, I really liked your second example, using the pipe and the
underscore closure shorthand together looks like a cool technique.

On Oct 30, 2007 8:29 AM, Janne Savukoski <janne@...> wrote:

> Hello,
>
> This feels a little stupid, and I'm sure there's something
> fundamentally n00b in this, but anyways... I've been experimenting
> with this kind of structure (note the pipe, '|', on 2nd line):
>
> <clip>
> 1: sw.sendMessage {
> 2:   new Message | { m =>
> 3:     m.setDisplayName(somename)
> 4:     m.setContent(format("Hello, %s! %s!", displayName, somecontent))
> 5:   }
> 6: }
> </clip>
>
> which is similar to
>
> 1: val m = new Message
> 2: m.setDisplayName(somename)
> 3: m.setContent(format("Hello, %s! %s!", displayName, somecontent))
> 4: sw.sendMessage(m)
>
> and
>
> 1: sw.sendMessage {
> 2:   val m = new Message
> 3:   m.setDisplayName(somename)
> 4:   m.setContent(format("Hello, %s! %s!", displayName, somecontent))
> 5:   m
> 6: }
>
>
> The last one was my favorite before the pipe, but it suffers from the
> explicit return. The second I don't like a bit as it exposes the name
> 'm' that is relevant only in the context of the 'sendMessage'
> invocation.
>
> In the first case the pipe—which returns the object itself—replaces an
> ad-hoc-initialization-block-using-anonymous-subclass. More generally,
> with pipe I can write a block with a 'private' reference to the
> context object. (or something...)
>
> The pipe is defined simply as
>
> implicit def pipe4Any[a](any: a) = new AnyRef { def |(f:a => Unit): a
> = { f(any); any } }
>
> Another nice use case was with logging:
>
> 1: rs.report(WARNING, root, format("Resource not found: %s",
> f.getAbsolutePath) | (warn(_)))
>
> where the message "Resource n..." is logged ('warn', shortcut to
> commons logging) while passed on to the report method. (No
> ad-hoc-initialization-block-using-anonymous-subclass here.)
>
> So, this is just such a trivial use case that I'm sure there's some
> standard way to do this. Please, feel free to show me the light. :)
>
>
> -janne
>



--
Rafael de F. Ferreira.
http://www.rafaelferreira.net/

 « Return to Thread: Private names