The problem
Why does this not compile in Java?
Optional<Integer> optionalInteger = Optional.of(1);
Optional<Number> opt...
For further actions, you may consider blocking this person and/or reporting abuse
I think you're missing a point here. Uncle Bob described this problem, but he used
List<Shape>
andList<Circle>
I believe. WhereShape
is a parent class for aCircle
, obviously. I don't remember where it was exactly, maybe in one of his Clean Coder videos. The point is, even thoughShape
andCircle
are related,List<Shape>
andList<Circle>
are not. And one is not a substitute for another. It is even dangerous, since that way you could add some other shape to what you think is aList<Shape>
but really isList<Circle>
, which could break your program. Reduced to absurdity: you and your spouse are related, but your lawyers (in case of divorce, for example) are not. :)With that in mind, I believe the correct Java solution would be:
Or even
And about Kotlin... I wonder how would Kotlin behave in the case with Lists above? :)
With all respect I think you've missed the point of the article. Of course it does not apply to
List
s, since they both produce and consume objects. It could apply to immutable lists, where you cannot add/set items, only get.My point was to show that classes with generic types that are used in producer role are not detected by Java compiler as safe to cast, when covariant types are used.
I see. Thanks for the clarification. I'm still not sure that this technique is really safe and won't be abused in some very unobvious ways, but that's completely different story. :)