in reply to Re: Moose type question
in thread Moose type question

I can tell you right now that the Moose core will not be changing this behavior

Nor should it. That's why Maybe[] and MooseX::UndefTolerant exist. The problem is that Maybe[] doesn't currently work with coercion, and that's the behaviour that should be changed.

Replies are listed 'Best First'.
Re^3: Moose type question
by stvn (Monsignor) on Jun 14, 2010 at 21:26 UTC
    The problem is that Maybe[] doesn't currently work with coercion, and that's behaviour that should be changed.

    The type 'Maybe[Foo]' is different the type 'Foo' and Maybe[`a] is a parameterized type, and parameterized types do not support deep coercion like that. We have discussed the topic of deep coercion, but it is simply deemed too magical and prone to action-at-a-distance type issues.

    Along with MooseX::UndefTolerant, it is also possible to subtype a Maybe[`a] type and then add coercions to that.

    subtype 'MaybeDateTime' => as 'Maybe[DateTime]'; coerce 'MaybeDateTime' => from 'St' => via { ... };
    Of course your coercions would need to account for the possibility of undef, but that shouldn't be too hard.

    -stvn

      Thanks. The above test script passes all tests with the following definitions. The redundancy is annoying, but it'll do until I get around to making/finding a proper trait/extension.

      BEGIN { package Class; use strict; use warnings; use Moose; has val => ( is => 'rw', isa => 'Num', required => 1, ); use Moose::Util::TypeConstraints; coerce __PACKAGE__ => from 'Num' => via { __PACKAGE__->new(val => $_) }; subtype 'Maybe'.__PACKAGE__ => as 'Maybe['.__PACKAGE__.']'; coerce 'Maybe'.__PACKAGE__ => from 'Num' => via { __PACKAGE__->new(val => $_) }; } BEGIN { package Container; use strict; use warnings; use Moose; has always => ( is => 'rw', isa => 'Class', coerce => 1, default => sub { Class->new(val => 0) }, ); has maybe => ( is => 'rw', isa => 'MaybeClass', coerce => 1, default => undef, ); }