6

This code (for checking the changed timestamp of the current directory):

my $date = ".".IO.changed.DateTime.yyyy-mm-dd but Dateish; 
say $date;

yields the error:

«Ambiguous call to 'gist(Str+{Dateish}: )'; these signatures all match:␤:  (Str:D: *%_)␤:(Dateish:D:   │ avalenn
                 | *%_)␤  in block <unit> at <tmp> line 1␤␤»

Without the Dateish mix in, the string is simply 2018-05-12. Using any other kind of Dateish function, like .week-year also yields a different error:

«Str+{Dateish}␤Invocant of method 'Bridge' must be an object instance of type 'Int', not a type      │ a3r0
                 | object of type 'Int'.  Did you forget a '.new'?␤  in block <unit> at <tmp> line 1␤␤»

Does it simply mean that you can't mix in a string with Dateish? I've done something similar with hours without a problem.

Christopher Bottoms
  • 11,218
  • 8
  • 50
  • 99
jjmerelo
  • 22,578
  • 8
  • 40
  • 86

1 Answers1

6

To answer your question, we should look at that role:

my role Dateish {
    has Int $.year;
    has Int $.month;     # should be int
    has Int $.day;       # should be int
    has Int $.daycount;
    has     &.formatter;

    ...
    multi method Str(Dateish:D:) {
        &!formatter ?? &!formatter(self) !! self!formatter
    }
    multi method gist(Dateish:D:) { self.Str }
    ...
}

So, role Dateish has several attributes, and the methods use those attributes to calculate their return values.

When you do $some-string but Dateish, you are not doing anything to initialize the attributes, and thus method calls that use them (potentially indirectly) fail in interesting ways.

How do you get a Dateish object from a DateTime then? Well, DateTime is one, already, or you can coerce to Date if that is what you want:

my $date = ".".IO.changed.DateTime.Date; say $date

You might also try to instantiate a Dateish by supplying all attributes, but I don't see any advantage over just using Date as intended.

moritz
  • 12,710
  • 1
  • 41
  • 63
  • Is there a way to mix-in an object instead of a type initializing it? Not in this case, since it seems that Dateish can't be initialized, only cloned... Besides, somehow I thought that mixing in a class performed some kind of initialization. What's the use case for this kind of mixins then? – jjmerelo May 12 '18 at 18:17