Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine multiple extractor objects to use in one match statement

Tags:

scala

Is it possible to run multiple extractors in one match statement?

object CoolStuff {
  def unapply(thing: Thing): Option[SomeInfo] = ...
}
object NeatStuff {
  def unapply(thing: Thing): Option[OtherInfo] = ...
}

// is there some syntax similar to this?
thing match {
  case t @ CoolStuff(someInfo) @ NeatStuff(otherInfo) => process(someInfo, otherInfo)
  case _ => // neither Cool nor Neat
}

The intent here being that there are two extractors, and I don't have to do something like this:

object CoolNeatStuff {
  def unapply(thing: Thing): Option[(SomeInfo, OtherInfo)] = thing match {
    case CoolStuff(someInfo) => thing match {
      case NeatStuff(otherInfo) => Some(someInfo -> otherInfo)
      case _ => None // Cool, but not Neat
    case _ => None// neither Cool nor Neat
  }
}
like image 622
Dylan Avatar asked Dec 11 '22 07:12

Dylan


1 Answers

Can try

object ~ {
  def unapply[T](that: T): Option[(T,T)] = Some(that -> that)
}

def too(t: Thing) = t match {
  case CoolStuff(a) ~ NeatStuff(b) => ???
}
like image 123
cchantep Avatar answered May 18 '23 14:05

cchantep