- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Re: Re: Abstract type list.
Tue, 2012-01-24, 09:39
Dear David,what will happen in case I have 4 type of foods?
Best Regards
2012/1/24 David Christiansen <david@davidchristiansen.dk>
Best Regards
2012/1/24 David Christiansen <david@davidchristiansen.dk>
Hi Edmondo,
> I would like to write something like the following
>
> class Dog extends Animal {
> type foodType = PackagedFood, Meat
> def eat(food:Meat) = println "The dog is happy"
> def eat(food: PackagedFood ) = println "The dog is sad"
>
> }
>
> How does one solve this problem?
In this particular case, can't you use an Either type? For example,
class Dog extends Animal {
type foodType = Either[PackagedFood, Meat]
def eat(food: foodType) = food match {
case Left(_) => println("The dog is happy")
case Right(_) => println("The dog is sad")
}
}
Nested Eithers can also build a list structure, but it's ugly.
/David
> what will happen in case I have 4 type of foods?
That was the nested list of Either I was mentioning. It's not
particularly appealing. Something like:
type foodType = Either[Meat, Either[ProcessedFood, Either[Broccoli,
Sandwich]]]
Some other possibilities include defining a little wrapper class
hierarchy:
abstract class foodType
case class MeatWrapper (m: Meat) extends foodType
case class ProcessedFoodWrapper (pf: ProcessedFood) extends FoodType
and so forth. This is also inconvenient for clients.
Do you have a practical use case here? My guess is that you are best
served by re-architecting your design a bit rather than by shoehorning
these big, complex types into it.
/David