Thread overview
Unable to use map() and array() inside a class-field's initializer.
Jul 14, 2022
realhet
Jul 14, 2022
Paul Backus
Jul 14, 2022
realhet
July 14, 2022

Hello,

Somehow it can't reach map and array inside a class field initializer. If I put that small expression inside a function, it works. If I encapsulate the initializer expression into a lambda and evaluate it right away, it also works. Only the nice form fails.

Why is that?

import std;

enum E{a, b, c}

static struct S{
    const E e;
    string otherProperties;
}

//trying to initialize an array inside

static if(1) class D{
  //this fails: Error: function `onlineapp.D.map!(E[]).map` need `this` to access member `map`
  auto x = [EnumMembers!E].map!(e => S(e)).array;
}

auto initialS(){
  return [EnumMembers!E].map!(e => S(e)).array;
}

class C{
  auto x = initialS; //this way it works
}

void main(){
    writeln((new C).x);
}
July 14, 2022

On Thursday, 14 July 2022 at 13:57:24 UTC, realhet wrote:

>

Hello,

Somehow it can't reach map and array inside a class field initializer. If I put that small expression inside a function, it works. If I encapsulate the initializer expression into a lambda and evaluate it right away, it also works. Only the nice form fails.

Why is that?

import std;

enum E{a, b, c}

static struct S{
    const E e;
    string otherProperties;
}

//trying to initialize an array inside

static if(1) class D{
  //this fails: Error: function `onlineapp.D.map!(E[]).map` need `this` to access member `map`
  auto x = [EnumMembers!E].map!(e => S(e)).array;
}

Simpler workaround:

  // Explicit type annotation:   vvv
  auto x = [EnumMembers!E].map!((E e) => S(e)).array;

This turns the lambda from a template into a normal function, which apparently is enough to un-confuse the compiler. Still unclear why it's getting confused in the first place, though.

July 14, 2022

On Thursday, 14 July 2022 at 14:41:53 UTC, Paul Backus wrote:

>

Explicit type annotation: vvv

Thank You!

I will remember that in case of weird errors I can try to help the compiler with type inference.