Private names
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