score:0

Accepted answer

yes, take a look at "matching on case classes" here: http://docs.scala-lang.org/tour/pattern-matching.html#matching-on-case-classes

from there:

abstract class notification
case class email(sender: string, title: string, body: string) extends notification
case class sms(caller: string, message: string) extends notification
case class voicerecording(contactname: string, link: string) extends notification

def shownotification(notification: notification): string = {
  notification match {
    case email(email, title, _) =>
      s"you got an email from $email with title: $title"
    case sms(number, message) =>
      s"you got an sms from $number! message: $message"
    case voicerecording(name, link) =>
      s"you received a voice recording from $name! click the link to hear it: $link"
  }
}

update: it's hard to know what you're looking for without a more concrete example... maybe this:

trait frontman
case object mickjagger extends frontman

trait band
case object rollingstones extends band

frontman match {
  case mickjagger => rollingstones
}

update, slightly cleaner:

abstract class band (val frontman: string)

object rollingstones extends band(frontman = "mick jagger")

val tobematched = "mick jagger"

tobematched match {
  // no need for if guard
  case rollingstones.frontman => println("we got the rolling stones singer!")
}

the if-guard is not needed since you can use an identifier directly in the pattern match. but it requires that it be a stable identifier (ex: val, object, literal... not var or def). so the original def frontman would not have worked. if the identifier had been just a val without an object prefix, then it would have needed backticks to differentiate it from a pattern variable.


Related Query

More Query from same tag