Re: When to use .new?
[email protected] (ToddAndMargo via perl6-users)
| Newsgroups | perl.perl6.users |
|---|---|
| Message-ID | <[email protected]> |
On 12/5/22 11:19, Ralph Mellor wrote: > I forgot to mention one other shortcut that is always available > if you do have to use `.new` (which is the case for most types). > > You can write: > ``` > my $foo = 42; > ``` > The `42` on the RHS of the `=` is the shortest way to create > an integer value corresponding to `42`. > > But you could also write: > ``` > my $foo = Int.new: 42; > ``` > It's odd, but you could that. You could also write: > > ``` > my Int $foo .= new: 42; > ``` > Note the `.=` instead of `=` and the `new` instead of `Int.new`. > > That is, if you constrain a variable's type, and want to initialize > that variable to a value of exactly that type, you don't have to > repeat the type name on the RHS of the `=` if you write it as above. > > For types that have literal forms it's not helpful. And for short type > names it's helpful, but only a little. But let's say you really wanted > to write out the full `NativeCall::Types::Pointer` and you wanted a > variable constrained to that type and initialized to have a value of > that type. Now it's a big deal: > > ``` > my NativeCall::Types::Pointer $foo .= new: 42; > ``` > > -- > raiph Hi Ralph, Thank you for the excellent explanation! Is there a list of what variables/object I have to use .new with and which ones I don't? -T