« Return to Thread: Private names

Re: Private names

by Robin Message :: Rate this Message:

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

Okay, I'm only getting started with Scala, but how about:

1: sw.sendMessage { m =>
2:     m.setDisplayName(somename)
3:     m.setContent(format("Hello, %s! %s!", displayName, somecontent))
4: }

With sendMessage defined as:
def sendMessage(setter:Message=>unit) {
        var msg=new Message()
        setter(msg)
        //..do something with msg
}

If you want to send subclasses of message, then the code ought to look
like:

1: sw.sendMessage[SubMessage] { m =>
2:     m.setDisplayName(somename)
3:     m.setContent(format("Hello, %s! %s!", displayName, somecontent))
4: }

With sendMessage defined as:
def sendMessage[T <: Message](setter:T=>unit) {
        var msg=new T()
        setter(msg)
        //..do something with msg
}

Alas, that doesn't compile. Any guru want o suggest how that
could/should be done?

Cheers,

Robin Message

On Wed, 2007-10-31 at 17:29 +0200, Janne Savukoski wrote:

> Hi Rafael!
>
> On 10/30/07, Rafael de F. Ferreira <rafael@...> wrote:
> > 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)
> > })
>
> Thanks for confirming that, I had no idea if it was a popular
> technique with Scala. I myself try to avoid it, as it feels a little
> intrusive and, well, 'blunt'. :) But it certainly is a smooth way.
>
>
> > Anyway, I really liked your second example, using the pipe and the
> > underscore closure shorthand together looks like a cool technique.
>
> Nice :) . Btw., if the method 'warn' wasn't overloaded, the syntax
> could be reduced into just '"foo" | warn'. Although, I'm thinking the
> name '|' may be a little confusing as it doesn't transform the
> source.. (Instead, if we named map+filter to pipe, it would be shell
> scripts all over again. :)
>
> But anyways, it's funny that there hasn't been more suggestions about
> some standard ways for replacing this proprietary hack. I'm just a
> Scala newbie still and I'm sure there's a lot of constructs and
> syntactic tricks I'm not aware of.
>
> -janne

 « Return to Thread: Private names