Hacker News new | ask | show | jobs
by jayd16 3681 days ago
Simple things like adding a list of Apples to a list of Fruits become non-trivial.
1 comments

Non-trivial? In Scala it would be:

    fruits ++= apples.map(_.asFruit)
That part is fine. The difficulty arises when you want to take out an apple from a list of fruits.
Why should you be able to do that?
Right, if you take type-safety first, you shouldn't be able to. But a list of abstract fruits has very limited usage without the ability to accessing concrete fruit instance. The adoption of downcasting in some OO languages came out from such needs, given that they lacked generic and/or algebraic types. And with that regard, I thought your solution didn't address the original covariance/contravariance problem (that is, want to have heterogeneous list of fruits and allowing to access concrete types of individual elements).

There are type-safe ways, like making a fruit a sum type of apple and banana, or using traits or type classes, etc. But is-a/has-a discussion seems a bit off from that.

> I thought your solution didn't address

FWIW, I didn't propose the original Scala snippet, so it isn't really “my” solution.

> the original covariance/contravariance problem

The problem is precisely preventing what you're trying to do, because it's unsafe.

Ah, ok, I mixed up you with continuational.

For this context, what I'm saying is that if you don't need to extract an apple from a list of fruits, then you can do it safely with inheritance, so whether using inheritance or delegation is irrelevant. Isn't it?