Skip to content

Instantly share code, notes, and snippets.

@antoniogamiz
Created July 20, 2019 08:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antoniogamiz/3b9fa8fa4a284ab84518480b0506a307 to your computer and use it in GitHub Desktop.
Save antoniogamiz/3b9fa8fa4a284ab84518480b0506a307 to your computer and use it in GitHub Desktop.
class A {
has $.verbose;
submethod BUILD (
:$verbose
) {
}
}
class B is A {
has $.attr;
submethod BUILD(
:$attr
) {
}
}
my $b = B.new(verbose => "dd", attr => "dddd");
say $b; # B.new(attr => Any, verbose => Any)
@uzluisf
Copy link

uzluisf commented Jul 20, 2019

Remember that if you want it to populate the attributes, you need:

  • to do the assignment in BUILD submethod's body:
class A {
    has $.verbose;
    submethod BUILD ( :$verbose ) {
        $!verbose = $verbose
    }
}

class B is A {
    has $.attr;
    submethod BUILD( :$attr ) {
        $!attr = $attr
    }
}

my $b = B.new(verbose => "dd", attr => "dddd");
say $b; # B.new(attr => "dddd", verbose => "dd")
  • to specify it in the method's signature:

For the class A's BUILD, you could do :verbose($!verbose) right in the BUILD's signature. The same for B. But isn't :verbose($!verbose) too verbose? You can use :$!verbose instead. I guess that's probably what you meant but missed the elusive ! in the named parameter and that's why you got B.new(attr => Any, verbose => Any).

class A {
    has $.verbose;
    submethod BUILD( :!$verbose ) { }
}

class B is A {
    has $.attr;
    submethod BUILD( :!$attr ) { }
}

my $b = B.new(verbose => "dd", attr => "dddd");
say $b; # B.new(attr => "dd", verbose => "dddd")

Per the docs,

be careful when using this auto-binding of attributes when the attribute may have special type requirements... Remember, default values will be assigned unless you specifically take care of this attribute, and that default value will be Any, which would cause a type error.

I think the use of the BUILD submethod is also discouraged. Instead, you might want to use the TWEAK submethod.

@antoniogamiz
Copy link
Author

Oooohh I see! Thanks a lot for taking the time with this! I really appreciate it :D.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment