logo
Free, unlimited AI code reviews that run on commit
git-lrc git-lrc GitHub Install Now We'd appreciate a star git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt

"Object::Pad::ClassAttr::Struct" - declare an "Object::Pad" class to be struct-like

Author

       Paul Evans <leonerd@leonerd.org.uk>

perl v5.40.1                                       2025-04-15                Object::Pad::ClassAttr::Struct(3pm)

Class Attributes

:Struct
          class Name :Struct ... { ... }

       Automatically applies the ":param" and ":mutator" attributes to every field defined on the class, meaning
       the constructor will accept parameters for each field to initialise the value, and each field will have
       an lvalue mutator method.

       In addition, the class itself gains the :strict(params) attribute, meaning the constructor will check
       parameter names and throw an exception for unrecognised names.

       Sinceversion0.04 a positional constructor class method called "new_values" is also provided into the
       class, which takes a value for every field positionally, in declared order.

          $obj = ClassName->new_values($v1, $v2, $v3, ...);

       This positional constructor must receive as many positional arguments as there are fields in total in the
       class; even the optional ones. All arguments are required here.

       Sinceversion0.05 the following options are permitted inside the attribute value parentheses:

       :Struct(readonly)

       Instances of this class do not permit fields to be modified after construction. The accessor is created
       using the ":reader" field attribute rather than ":mutator".

Description

       This module provides a third-party class attribute for Object::Pad-based classes, which applies some
       attributes automatically to every field added to the class, as a convenient shortcut for making
       structure-like classes.

Name

       "Object::Pad::ClassAttr::Struct" - declare an "Object::Pad" class to be struct-like

Synopsis

          use Object::Pad;
          use Object::Pad::ClassAttr::Struct;

          class Colour :Struct {
             # These get :param :mutator automatically
             field $red   = 0;
             field $green = 0;
             field $blue  = 0;

             # Additional methods are still permitted
             method lightness {
                return ($red + $green + $blue) / 3;
             }
          }

          my $cyan = Colour->new( green => 1, blue => 1 );

          # A positional constructor is created automatically
          my $white = Colour->new_values(1, 1, 1);

See Also