Correct syntax in pattern matching

Hi all,

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

What is the correct syntax ?

Thanks in advance,

}

What is the price you actually want for a Glace? To cover the cases, you can use

case Glass(Some(Chantilly)) => ???
case Glass(Some(Chocolat)) => ???
case Glass(None) => ???

regards,
Siddhartha

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 ?

Thanks for your help.

Their are two ways to do this. Either use unapply to decompose and obtain all members so:

f match {
  case PetiteFaim(p) => calculatePrice(p)
  case EntreePlat(e,p) => calculateSumOfPrices(e,p)
  case _ => ???
}

or assign the matched class to a new object so:

f match {
  case x@PetiteFaim(_) => calculatePrice(x.p)
  case x@EntreePlat(_,_) => calculateSumOfPrices(x.e,x.p)
  case _ => ???
}

The example above is not idiomatic. You can however match on type only so:

f match {
  case x:PetiteFaim => calculatePrice(x.p)
  case x:EntreePlat => calculateSumOfPrices(x.e,x.p)
  case _ => ???
}

For more information see: https://docs.scala-lang.org/tour/pattern-matching.html

HTHs

Thanks for your detailed answer and the link.

Best regards.