Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to create class aliases dynamically?

Tags:

raku

Got this class:

class Mass-lb is Mass {
    method new(Rat:D() $value = 1.0) {
        self.bless(
            :abbr('lb'),
            :base_value(453.59237),
            :$value,
        );
    }
}

I have created aliases like this:

class Mass-lbs is Mass-lb { }
class Mass-pound is Mass-lb { }
class Mass-pounds is Mass-lb { }
class Mass-pnds is Mass-lb { }

But I'd prefer to do something like this:

my @lb-syn = < lbs pounds pound pnds >;
for @lb-syn {
    EVAL 'class ::("Mass-$_") is Mass-lb {}';
}

This throws an error:

Name ::("Mass-$_") is not compile-time known, and can not serve as a package name

PHP has a built-in for creating aliases: https://www.php.net/manual/en/function.class-alias.php

I couldn't find anything similar for raku.

like image 976
StevieD Avatar asked Sep 07 '26 14:09

StevieD


1 Answers

In RakuAST there's a class that you can call to create a new type. But that the RakuAST branch hasn't landed yet.

Until then, your approach using EVAL is valid, you just need to make it a bit simpler:

class Mass-lb { }
BEGIN "constant Mass-$_ = Mass-lb".EVAL
  for <lbs pounds pound pnds>;
my $mlb = Mass-lbs.new;
  1. Make sure the aliases are created at BEGIN time.
  2. No need to subclass, you can use a constant for aliasing.
  3. Since constants are our by default, they're visible outside of the EVAL.
like image 160
Elizabeth Mattijsen Avatar answered Sep 11 '26 05:09

Elizabeth Mattijsen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!