The problem of animals and foods
this is a short post that is dealing with a classic riddle.
I was thinking on this riddle when I was trying to figure out a Scala feature. we are having (at Sela Group) a small Scala study group led by Israel Tabadi and while we were going over Scala’s abstract type (which is by the way a cool implementation) I was thinking about the .NET equivalent solution.
I will use the problem of "animals and foods" (taken from here) as an anchor’s point.
The problem: assuming an Animal with a method, Eat, which eats some food. and the riddle is, how can you restrict a Cow (which derived from an Animal), to eat nothing but Grass (at compile time). A Cow can’t eat an arbitrary food like Fish.
the idea is to restrict a Cow to a specialize type of food which is Grass.
the Scala version is available here.
now take your time and think of how can you solve it using .NET and Generics?
the solution is to assign the Cow’s type to Grass (as simple as it is, sometimes it can slip away).
the solution is present on the following snippet:
the following snippet is the main method part:
and the result is: