Search code examples
propertiesrefd

Properties and ref return values in D


Testing the following in D

import std.stdio;

struct S
{
    int _val;
    @property ref int val() { return _val; }
    @property void val(int v) { _val = v; writeln("Setter called!"); }
}

void main()
{
    auto s = S();
    s.val = 5;
}

yields "Settter called!" as the output.

What rule does the compiler use to determine whether to call the first or the second implementation?


Solution

  • Here you are providing two @property methods, one accepts an argument, the other does not. When doing s.val = 5;, what you're actually doing is s.val(5), but as val is a @property you can write it as a property rather than a method call (see http://d-programming-language.org/function.html#property-functions). From s.val(5) the compiler can do standard overload resolution - see http://d-programming-language.org/function.html#function-overloading.