On 04/29/2016 06:02 PM, Rowan Collins wrote: > Hi Dominic, > > Sorry, I think this may have got sent too early by mistake; please > ignore the duplicate! > > Also, it's crossed in the post with your next message, but I'll send > it anyway, in case it helps anyone understand. > > > Dominic Grostate wrote on 29/04/2016 16:45: >> It's not insane, it's liskov substitution. But that is an insane >> example, typical of Java to create a type that extends it's parent by >> adding value constraints.. directly violating the principle. > > > Let's translate the covariant example code into English: > > function addPiToList(List<Number> $list): void > // "I am a function that accepts any list of Numbers" > { > $list->add(3.1415); > // "To the list I was given, add the Double 3.1415, which is a kind of > Number" > } > > $li = new List<Integer>; > // "This is a new list of Integers" > addPiToList($li) > // "You asked for a list of Numbers; Integers are Numbers, so I can > give you my list" > > So far, so reasonable. But now lets see what gets executed: > > $list->add(3.1415); > // "To the list of Integers you gave me, I will add the Double 3.1415" > // "Oops! A Double isn't allowed in your list, I will now produce a > Type Error" > > > > Now the same with the contravariant List<? super Double> example: > > function addPiToList(List<? super Double> $list): void > // "I am a function that accepts a list of any category, as long as > that category includes Doubles" > { > $list->add(3.1415); > // "To the list I was given, add the Double 3.1415" > } > > $ln = new List<Number>; > // "This is a new list of Numbers, it can mix Integers and Doubles, > because they are both types of Number" > addPiToList($ln) > // "You asked for a list that can contain Doubles; my list can contain > any Number, including Doubles, so I can give you my list" > > And inside the function: > > $list->add(3.1415); > // "To the list of Numbers you gave me, I will add the Double 3.1415" > // "Yay, it worked. :)" > > > Contravariance always seems counterintuitive, but it turns out it > really is the appropriate constraint in certain situations. indeed, thank you for this very detailed explanation. can this also be useful/makes sense for declaring a class? (eg: class List<? super Double> {}) maybe an abstract class ? or is it just for parameters ? > > Regards,
-- Mathieu Rochette