From documentation.
You can match on the type like so:
sealed trait Device
case class Phone(model: String) extends Device:
def screenOff = "Turning screen off"
case class Computer(model: String) extends Device:
def screenSaverOn = "Turning screen saver on..."
def goIdle(device: Device): String = device match
case p: Phone => p.screenOff
case c: Computer => c.screenSaverOn
It is a convention to use the first letter of the type as the case identifier (p and c in this case).
Question:
Why do we have a need for separate identifiers p
and c
here? Why cant we achieve the same with device.screenOff
or device.screenSaverOn
like in the case of a normal pattern matching?