Cloning Objects in Raku

I wouldn't use anything other than clone to clone objects. clone is a proto method defined by Mu, but it's up to its subtypes to implement its behaviour in this case, as cloning the object does clone the array attributes, but not in the way you want. As such, you can write your own clone multis that behave like you expect:

# Group
multi method clone(::?CLASS:D: --> ::?CLASS:D) {
    my ::?CLASS:D $clone .= new;
    $clone.add-item: .clone for @!group;
    $clone
}

# GroupOfGroups
multi method clone(::?CLASS:D: --> ::?CLASS:D) {
    my ::?CLASS:D $clone .= new;
    $clone.add-group: .clone for @!multi-group;
    $clone
}

::?CLASS here is a symbol that, when used in classes, is an alias for the class itself, with :D restricting the type to instances only.


Hi @julio a careful reading of the docs led me to this ... works like a charm:

method clone { nextwith :foo(@!foo.clone), :bar(%!bar.clone), |%_  }

(this also helped me to understand the rational behind “restricted” language help for deep cloning)

Tags:

Object

Clone

Raku