why is this cast required?
Dejan Lekic
dejan.lekic at gmail.com
Fri Sep 25 13:04:28 UTC 2026
On Friday, 25 September 2026 at 11:14:50 UTC, DanielG wrote:
> ```d
> alias IntFunc = int delegate();
>
> void exec(IntFunc[] funcs) {}
>
> void main()
> {
> int two() => 2;
>
> exec(
> // why do I have to cast to the exact type that exec()
> already takes?
> cast(IntFunc[])
> [
> () => 1,
> () => two(),
> ]);
> }
> ```
>
> Without the cast, the error is:
>
>>Error: incompatible types for `(() => 1) : (() => two())`: `int
>>function() pure nothrow @nogc @safe` and `int delegate() pure
>>nothrow @nogc @safe`
Unfortunately you've hit a limitation of how the compiler
propagates the expected type into an array literal used as a
function argument.
You can avoid the cast by explicitly making the first lambda a
delegate:
```d
exec([
delegate () => 1,
() => two(),
]);
```
, or by using an explicitly typed variable, which also provides
the necessary context:
```d
IntFunc[] funcs = [
() => 1,
() => two(),
];
exec(funcs);
```
Why? - Because `() => 1` needs no enclosing context so it is
inferred as a function pointer, while `() => two()` calls a
non-static nested function and will be treated as a delegate by
the compiler.
More information about the Digitalmars-d-learn
mailing list