1 day ago

Why doesn't this work?

import std;

struct Optional(T)
{
    T value;
    bool hasValue;
}

auto map(alias fn, T)(Optional!T m)
{
    alias U = ReturnType!fn;

    if (m.hasValue) {
        return Optional!U(fn(m.value), true);
    } else {
        return Optional!U();
    }
}

void main()
{
    auto x = Optional!string("123", true);
    auto y = x.map!(it => 123);
    writeln(y);
}

Error:

onlineapp.d(11): Error: template instance `onlineapp.main.ReturnType!(__lambda_L23_C21)` does not match template declaration `ReturnType(alias func)`
  with `func = __lambda_L23_C21(__T1)(it)`
  must satisfy the following constraint:
`       isCallable!func`
    alias U = ReturnType!fn;
              ^
onlineapp.d(23): Error: template instance `onlineapp.main.map!((it) => 123, string)` error instantiating
    auto y = x.map!(it => 123);
              ^

This error message makes noooooo sense to me. At all. It's gibberish. How is a lambda not callable?! This is really frustrating, as something that works absolutely trivially in any other language.

It's something that I've ran against with D time and time again: I get an inscrutable error or problem that is only solved by “just” knowing the right incantation to use, anytime I try to do something even slightly unorthodox, and it makes D really annoying to use if you’re new to it.

Please ignore the bad encapsulation in the struct, it's just a minimal example. Thank you

1 day ago

On Saturday, 26 July 2025 at 23:08:35 UTC, luafyn wrote:

>
alias U = ReturnType!fn;

ReturnType!(fn!T) works

id avoid being this explicit with types tho, type inference is unidirectional in d, its best to lean into it and follow the natural flow