The object operator
BBasile via Digitalmars-d
digitalmars-d at puremagic.com
Thu Aug 13 23:46:13 PDT 2015
On Friday, 14 August 2015 at 04:17:25 UTC, TheHamster wrote:
> For class types, a special operator is defined to return the
> class object for method calls rather than the return value from
> the call itself. The use of the operator places the return
> types in special variables to be accessed easily. The operator
> is simply a syntax helper and is along the lines of UFCS.
>
> e.g.,
>
> class myClass
> {
> Do(int x) { return x + 2; }
>
> }
>
> auto myObj = new myClass();
> assert(@@myObj.Do(3).Do(4).Do(5) == 7);
>
> Of course, such a silly example is not very helpful but
> demonstrates the concept.
>
> To make such a syntax work well, I believe one then needs a
> further operator to access the last return value.
>
> e.g.,
>
> assert(@@myObj.Do(3).Do(@).Do(@2) == 9);
>
> Where the same symbol is used for there return value
> placeholders and indices are used to access nested calls return
> value with @ defaulting to @1.
>
> Essentially such syntax allows for easily doing nested calls.
>
> The only down side is that the operator could only be used on
> one method call at a type in the nesting. (or multiple or
> parameritized operators would be required)
>
> Obviously @ would not be the symbol of choice.
Actually you can already do that by encapsulating a field an
playing with a property setter that also return `this`:
---
class Foo
{
private int _field;
Foo bar(int x) {_field += x + 2; return this;}
int bar(){return _field;}
}
void main(string[] args)
{
auto foo = new Foo;
// same as assert(@@myObj.Do(3).Do(@).Do(@2) == 9);
assert(foo.bar(3).bar(foo.bar).bar(foo.bar).bar == 9);
auto f = new Foo;
// same as assert(@@myObj.Do(3).Do(@).Do(@2) == 9);
with(f) {assert(bar(3).bar(bar).bar(bar).bar == 9);}
}
---
More information about the Digitalmars-d
mailing list