Open tux-rampage opened 2 years ago
I found these snippets:
It seems that this works when declaring the Template parameter covariant. Not sure if that is correct, but I thought a union is something different than inheritance, or am i getting something wrong?
I found these snippets:
Say you have a Box<T>
, with a method like replaceContents(T $contents)
. If we allowed passing a Box<Chocolates>
to a method accepting Box<Chocolates|Flowers>
it could have replaced chocolates with flowers, while the code outside would still believe it had a box of chocolates.
Variance is not about just inheritance, it is about type relations e.g. subtypes.
@weirdan Thanks for taking time to explain. I reviewed the psalm docs about covariance and it seems to be the correct use case here.
Anyways I've stumbled over another issue with the following snippet: https://psalm.dev/r/26590496a3
I know this is because of:
But @template-covariant doesn't get rid of all errors – if you add it to the first example, you get a new error (...) – complaining that you're attempting to use a covariant template parameter for function input. That’s no good, as it means you're likely altering the collection somehow (which is, again, a violation).
Is there a way to Type the affected callable parameter covariant-friendly, so that psalm errors when the wrong closure type is passed?
Or as a different and better approach: Can the transactional
method somehow be typed that it must not change the class state (so that it doesn't mater whether the closure mutates its input or not).
I found these snippets:
Not sure if this worked before. When declaring a templated type with a union type parameter, psalm reports an incorrect type mismatch, but it works when writing each template variant verbosively as union type:
https://psalm.dev/r/55488318f8