相关疑难解决方法(0)

组合多个提取器对象以在一个匹配语句中使用

是否可以在一个匹配语句中运行多个提取器?

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
}
Run Code Online (Sandbox Code Playgroud)

这里的意图是有两个提取器,我不必做这样的事情:

object CoolNeatStuff {
  def unapply(thing: Thing): Option[(SomeInfo, OtherInfo)] = thing match {
    case CoolStuff(someInfo) => thing match {
      case NeatStuff(otherInfo) => Some(someInfo -> otherInfo)
      case _ => None // …
Run Code Online (Sandbox Code Playgroud)

scala

3
推荐指数
2
解决办法
234
查看次数

标签 统计

scala ×1