Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an enum from its name not value

Tags:

enums

raku

Given the enumeration

enum NATO (:alpha<A>, :bravo<B>, :charlie<C>, :delta<D>);

it's possible to easily set a variable by literally typing one of the names, or by passing one of the values to the enum object:

my $a = alpha;
my $b = NATO('B');

say $a;        # ↪︎ alpha
say $b;        # ↪︎ bravo
say $a.value;  # ↪︎ A
say $b.value;  # ↪︎ B

Besides using EVAL and given a Str that corresponds to one of the enums, how could I create $c to be an enum value equivalent to charlie?

my $x = 'charlie';
my $c =  ...
like image 374
user0721090601 Avatar asked Apr 20 '19 02:04

user0721090601


People also ask

Is enum value or reference?

An enum type is a distinct value type (§8.3) that declares a set of named constants. declares an enum type named Color with members Red , Green , and Blue .

Can enum names be numbers?

Enum instances must obey the same java language naming restrictions as other identifiers - they can't start with a number. If you absolutely must have hex in the name, prefix them all with a letter/word, for example the enum class itself: public enum Tag { Tag5F25, Tag4F, ... }

What does enum from name do?

The java.lang.Enum.name() method returns the name of this enum constant, exactly as declared in its enum declaration.

What does enum name () return?

name. Returns the name of this enum constant, exactly as declared in its enum declaration. Most programmers should use the toString() method in preference to this one, as the toString method may return a more user-friendly name.


1 Answers

You can treat it as a Hash:

my $c = NATO::{$x};
like image 60
Curt Tilmes Avatar answered Oct 09 '22 11:10

Curt Tilmes