小编wbn*_*wbn的帖子

Perl 6和`multi method new`

我有一个Price封装了一个类的类Int.我也希望它有Num和的构造函数Str.我认为我可以通过制作Price::new具有各种类型约束的多方法来实现这一点,但这不是我期望的行为.它看起来像Price.new完全跳过构造函数并直接BUILD跳过,绕过了构建逻辑.

我知道从其他Perl 6代码中multi method new可以接受使用.但是,我还没有找到具有不同类型约束的多态构造函数的示例.如何重写此代码以强制它在构造函数中使用转换逻辑?

LIB/Price.pm6

#!/usr/bin/env perl6 -w

use v6;

unit class Price:ver<0.0.1>;

class X::Price::PriceInvalid is Exception {
    has $.price;

    method message() {
        return "Price $!price not valid"
    }
}

# Price is stored in cents USD
has $.price;

multi method new(Int $price) {
    say "Int constructor";
    return self.bless(:$price);
}

multi method new(Num $price) {
    say "Num constructor";
    return self.new(Int($price * 100));
} …
Run Code Online (Sandbox Code Playgroud)

polymorphism perl6

8
推荐指数
2
解决办法
201
查看次数

使用环境变量构建配置类的更简洁方法?

我有一个Configuration读取环境变量的类:

class Configuration {
    has $.config_string_a;
    has $.config_string_b;
    has Bool $.config_flag_c;

    method new() {
        sub assertHasEnv(Str $envVar) {
            die "environment variable $envVar must exist" unless %*ENV{$envVar}:exists;
        }

        assertHasEnv('CONFIG_STRING_A');
        assertHasEnv('CONFIG_STRING_B');
        assertHasEnv('CONFIG_FLAG_C');

        return self.bless(
            config_string_a => %*ENV{'CONFIG_STRING_A'},
            config_string_b => %*ENV{'CONFIG_STRING_B'},
            config_flag_c => Bool(%*ENV{'CONFIG_FLAG_C'}),
        );
    }
}

my $config = Configuration.new;

say $config.config_string_a;
say $config.config_string_b;
say $config.config_flag_c;
Run Code Online (Sandbox Code Playgroud)

是否有更简洁的方式来表达这一点?例如,我在检查中重复环境变量名称和构造函数的返回值.

我可以很容易地看到编写另一个更通用的类,它封装了config参数的必要信息:

class ConfigurationParameter {
    has $.name;
    has $.envVarName;
    has Bool $.required;

    method new (:$name, :$envVarName, :$required = True) {
        return self.bless(:$name, :$envVarName, :$required); …
Run Code Online (Sandbox Code Playgroud)

perl6

7
推荐指数
2
解决办法
138
查看次数

标签 统计

perl6 ×2

polymorphism ×1