gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:48:16 25 4
gpt4 key购买 nike

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

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
}

这里的目的是有两个提取器,我不必做这样的事情:
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
}
}

最佳答案

可以尝试

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

def too(t: Thing) = t match {
case CoolStuff(a) ~ NeatStuff(b) => ???
}

关于scala - 组合多个提取器对象以在一个匹配语句中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49058205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com