Search code examples
d

Does D have IIFE's?


JavaScript has Immediately invoked function expressions, they look like this : (function(){})();

I was wondering if something similar could be achieved in D. Failing that, a bonus question would be : Can I achieve the 'Revealing Module' design pattern in Dlang, or is this exclusive to JavaScript ?

I tried using pretty much the JS syntax.

import std.stdio;
void main()
{
    (function(){
        return "hello";
    })();
}

I got no result, but it seemed to compile fine in the online code playground I used.


Solution

  • Yes, it is possible to do the same things in D as in Javascript, and the syntaxes are very similar too - as you can see with your working code (like I said in the comment, the reason why you don't see anything is simply that your function didn't do anything!)

    You can do the revealing module thing too, and arguably D's standard library does this with what it calls "voldemort types" - a private type declared inside a function that is returned to the outside. But doing it exactly like Javascript is unnecessary since D has built in modules, classes, etc!

    I have used the IIFE pattern in D in a few places to allow statements where the grammar only allows an expression, for example in a loop clause or a mixin construct. Also useful when initializing static variables sometimes. It is an easy way to do complex work in a single assignment.

    But when it comes to details hiding, since D has modules and its modules have private members, it is usually easier and nicer to just use it.