betterC question

Jacob Carlborg doob at me.com
Thu Nov 19 09:23:25 UTC 2020


On Thursday, 19 November 2020 at 00:20:50 UTC, Dibyendu Majumdar 
wrote:
> On Thursday, 19 November 2020 at 00:18:54 UTC, rikki cattermole
>>
>> You don't need the brackets to call a function (and with a 
>> little help from UFCS):
>>
>> void main() {
>> 	import std.stdio;
>> 	
>> 	"Hello!".writeln;
>> 	writeln;
>> }
>
> Okay thanks. Bad idea IMO.

Yes, calling `writeln` like that is a bad idea. That was a bad 
example.

But the actual reason is, this is how D implements properties 
[1]. Any function that doesn't take an argument can be called 
without parentheses. Any function which takes a single argument 
can be called like setting a field. Here's an example:

struct Color
{
     private uint hex;

     int red()
     out(result; result >= 0 && result <= 255) // assert that the 
result is within bounds
     {
         return (hex & 0xFF0000) >> 16;
     }

     void red(int value)
     in(value >= 0 && value <= 255) // assert that the value is 
within bounds
     {
         hex = (hex & 0x00FFFF) | (value << 16);
     }

     // similar functions for green and blue
}

void main()
{
     Color color;
     color.red = 255;
     assert(color.red == 255);
}

[1] https://en.wikipedia.org/wiki/Property_(programming)

--
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list