I have the following definitions:
sealed trait Supplement
case object Chocolat extends Supplement
case object Chantilly extends Supplement
sealed trait Dessert
case object SaladeDeFruits extends Dessert
case object Cafe extends Dessert
case class Glace(supp: Option[Supplement]) extends Dessert
Each dessert has a price. I must screen the desserts to get the correct price.
I wrote:
def prixDessert(d: Dessert): Int = {
d match {
case Cafe => 1
case SaladeDeFruits => 4
case Glace ???
}
I have a problem with the Glace case
case Glace(_) is syntactically correct but not programmatically.
case Glace(Chantilly) raises “pattern type is incompatible with expected type; found : fr.istic.si2.tp2.restaurant.Chantilly.type required: Option[fr.istic.si2.tp2.restaurant.Supplement]” error
case Glace(Option(Chantilly)) is not good and the same stands for case Glace(Option(Supplement(Chantilly))) or case Glace(Supplement(Chantilly)) or case Glace.Chantilly
Thanks for your answer.
My code is now:
d match {
case Cafe => 1
case SaladeDeFruits => 4
case Glace(Some(Chantilly)) => 7
case Glace(Some(Chocolat)) => 6
case Glace(None) => 5
}
I have another question.
How to get the elements of a class when you have subclasses ?
I have the following:
sealed trait Formula
case class PetiteFaim(p: Plat) extends Formula
case class EntreePlat(e: Entree, p: Plat) extends Formula
case class PlatDessert(p: Plat, d: Dessert) extends Formula
case class Complete(e: Entree, p: Plat, d: Dessert) extends Formula
Depending of the type of Formula, I want to make a different treatment do the data contained in by the Formula
In pseudo code I want
f match {
case PetiteFaim() => calculatePrice(f.p)
case EntreePlat() => calculateSumOfPrices(f.e,f.p)
…
}
Unfortunately, the (f.p) syntax is wrong. What would be the right one ?