This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Re: Re: Abstract type list.

1 reply
edmondo1984
Joined: 2011-09-14,
User offline. Last seen 28 weeks 3 days ago.
Dear David,what will happen in case I have 4 type of foods?
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

David Christiansen
Joined: 2010-11-22,
User offline. Last seen 42 years 45 weeks ago.
Re: Abstract type list.

> 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

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland