method chaining

Jonathan M Davis jmdavisProg at gmx.com
Mon Nov 8 11:54:00 PST 2010


On Monday, November 08, 2010 11:39:43 spir 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);	///////
>     writeln(c);
> }
> 
> Well, the example is somewhat artificial, but this idiom is highly useful.
> 
> 
> Denis
> -- -- -- -- -- -- --
> vit esse estrany ☣
> 
> spir.wikidot.com

If you change it to (new C(1)).set(3), it should work. It should be noted, 
however, that there are several bugs relating to returning this from a function 
(primarily with regards to invariants IIRC), so method chaining doesn't always 
work when it should, but once the appropriate compiler bugs are fixed, it should 
work just fine.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list