method chaining

Steven Schveighoffer schveiguy at yahoo.com
Mon Nov 8 11:48:43 PST 2010


On Mon, 08 Nov 2010 14:39:43 -0500, spir <denis.spir at gmail.com> wrote:

> Hello,
>
> I don't understand why the compiler refuses the code below, with the  
> error
> __trials__.d(33): found '.' when expecting ';' following statement
> (Note that method set returns this.)
>
> class C {
>     int i,j;
>     this (int i) {
>         this.i = i;
>     }
>     C set (int j) {
>         this.j = j;
>         return this;
>     }
>     override string toString () {
>         return format("C(%s,%s)", i,j);
>     }
> }
>
> void main () {
>     c = new C(1).set(3);	///////

To the compiler, this means:

c = new (C(1).set(3));

What you want is:

c = (new C(1)).set(3);

Java implies this, but D does not.

-Steve


More information about the Digitalmars-d-learn mailing list