Type::Tiny Tricks #2: Types Are Objects

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.


Note that this is only true for Moose types.
perl types are just classes (i.e. packages), not objects.

Having them as objects is purely optional, but they need to be defined as class mandatory.

Leave a comment

About Toby Inkster

user-pic I'm tobyink on CPAN, IRC and PerlMonks.