📘 Typed variables in Perl 6

This is how you declare a typed variable:

my Int $x;

Here, a scalar container $x may only hold an integer value. Attempts to assign it a value that is not an integer leads to an error:

my Int $x;
$x = "abc"; # Error: Type check failed in assignment to '$x';
            # expected 'Int' but got 'Str'

For typecasts, a respective method call is quite handy. Remember that while $x holds an integer, it is treated as a container object as a whole, which is why you may use some predefined methods on it. The same you can do directly on a string. For example:

my Int $x;
$x = "123".Int; # Now this is OK
say $x; # 123

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s