c3c icon indicating copy to clipboard operation
c3c copied to clipboard

Retrieving the name of an associated value of an enum with reflection?

Open Elusive239 opened this issue 1 month ago • 5 comments

Currently, for enums you can get the types of their associated values by doing enum.associated, but currently there isn't a way to get their fields names so they can't be iterated. Maybe associated should return an array of structs that contains the type & the field name?

example:

$foreach $x : $EnumType.associated:
    var $AssociatedType = $typefrom($x.type);
    $foreach $value : $EnumType.values :
        $AssociatedType $v = $value.$eval($x.name);
        // ... further operations here
    $endforeach
$endforeach

Alternatively it could be split into enum.associated_fields & enum.associated_types or something similar.

Elusive239 avatar Nov 09 '25 18:11 Elusive239

This could possibly be done using the same mechanism as getting all members, except there is no "set" method for it.

lerno avatar Nov 12 '25 13:11 lerno

So something like MyEnum.associated_values[0].get(MyEnum.FOO) which would be the same as MyEnum.FOO.a assuming a is the first associated value? That'd be good

Book-reader avatar Nov 12 '25 23:11 Book-reader

This is now available:

enum Foo : (String x, int val)
{
  ABC = { "Hello", 3 },
  DEF = { "World", -100 },
}

fn void main()
{
  String hello = Foo.membersof[0].get(Foo.ABC); // "Hello"
  io::printn(hello);
  $foreach $member : Foo.membersof:
    io::printn($member.nameof);
    io::printn($member.type.nameof);
    io::printn($member.get(Foo.DEF));
  $endif
}

Will print

Hello
x
String
World
val
int
-100

lerno avatar Nov 13 '25 12:11 lerno

Please try it out.

lerno avatar Nov 13 '25 12:11 lerno

seems to work with what I've tried

Book-reader avatar Nov 25 '25 07:11 Book-reader