Type::Tiny Tricks #2: Types Are Objects

This is a very old article. It has been imported from older blogging software, and the formatting, images, etc may have been lost. Some links may be broken. Some of the information may no longer be correct. Opinions expressed in this article may no longer be held.

When you use code like this:

   package Local::Eg2;
   use Moose;
   use Types::Standard -types;
   has foo => (
      is      => "ro",
      isa     => Int,
      coerce  => 1,

Perhaps you don’t think very much about what that bareword Int is actually doing. Well, it’s a function that returns a blessed object. This object is used by Moose to check whether values are integers. Yes, Moose uses the object, and you can use it too!

The object returned by Int is a type constraint object, blessed into the Type::Tiny class which offers various useful methods. Here’s an example:

   Int->assert_valid( $counter );

The assert_valid method will throw an exception if $counter is not an integer. If you’d rather return a boolean instead of throwing an exception, use:

   Int->check( $counter )

And so you see, type constraints are not just useful for using with your OO framework’s has keyword – you can use them for plenty of other things too! You could use them perhaps for validating arguments to a function. Or use them for checking each row of a CSV file conforms to your expectations.