method chaining

Tomek Sowiński just at ask.me
Mon Nov 8 11:51:08 PST 2010


spir napisał:

> 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);	///////
>     writeln(c);
> }
> 
> Well, the example is somewhat artificial, but this idiom is highly useful.

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

-- 
Tomek


More information about the Digitalmars-d-learn mailing list