Scala 在匹配多个案例时提取参数以供理解 类
Scala extract the parameter in for comprehension when match multiple cases classes
我有一个带有多个案例的密封特征实现 classes,每个案例 class 都有自己的参数,其中一些具有相同类型的参数(我想提取,在这种情况下:Trigger
),其中一些没有。
sealed trait Event
object MyTrait {
final case class EventA(context: Context) extends Event
final case class EventB(trigger: Trigger) extends Event
final case class EventC(trigger: Trigger) extends Event
final case class EventD(trigger: Option[Trigger] = None) extends Event
...
final case class EventZ(factor: Factor) extends Event
}
逻辑流程处理如下:
event match {
case ev @(_: Event.EventA | _: Event.EventB |
_: Event.EventC | _: Event.EventD) =>
val amount = for {
count1 <- countThis
count2 <- countThat
// My logic added here
_ <- handleSomeTypeOfEvent(ev.trigger) // Doesn't work due to difference in implementations of event types
} yield res + another
case _ => doSomethingElse()
}
我需要在 for comprehension 中添加一个函数,该函数需要一个 Trigger
作为参数。但是在匹配的情况下,并非所有事件都包含 Trigger
参数,EventD
甚至以 Option[]
.
的形式包含它
是否有任何解决方案可以解决此问题而不解耦事件类型匹配并为每个案例复制 for 理解逻辑?
我认为您可以添加 extractTrigger
函数并更改 handleSomeTypeOfEvent
的签名以接受 Option[Trigger]
值:
def extractTrigger(event: Event): Option[Trigger] =
event match {
case EventB(trigger) => Some(trigger)
case EventC(trigger) => Some(trigger)
case EventD(trigger) => trigger
case _ => None
}
def handleSomeTypeOfEvent(maybeTrigger: Option[Trigger]): String = ???
val ev: Event = ???
handleSomeTypeOfEvent(extractTrigger(ev))
我有一个带有多个案例的密封特征实现 classes,每个案例 class 都有自己的参数,其中一些具有相同类型的参数(我想提取,在这种情况下:Trigger
),其中一些没有。
sealed trait Event
object MyTrait {
final case class EventA(context: Context) extends Event
final case class EventB(trigger: Trigger) extends Event
final case class EventC(trigger: Trigger) extends Event
final case class EventD(trigger: Option[Trigger] = None) extends Event
...
final case class EventZ(factor: Factor) extends Event
}
逻辑流程处理如下:
event match {
case ev @(_: Event.EventA | _: Event.EventB |
_: Event.EventC | _: Event.EventD) =>
val amount = for {
count1 <- countThis
count2 <- countThat
// My logic added here
_ <- handleSomeTypeOfEvent(ev.trigger) // Doesn't work due to difference in implementations of event types
} yield res + another
case _ => doSomethingElse()
}
我需要在 for comprehension 中添加一个函数,该函数需要一个 Trigger
作为参数。但是在匹配的情况下,并非所有事件都包含 Trigger
参数,EventD
甚至以 Option[]
.
是否有任何解决方案可以解决此问题而不解耦事件类型匹配并为每个案例复制 for 理解逻辑?
我认为您可以添加 extractTrigger
函数并更改 handleSomeTypeOfEvent
的签名以接受 Option[Trigger]
值:
def extractTrigger(event: Event): Option[Trigger] =
event match {
case EventB(trigger) => Some(trigger)
case EventC(trigger) => Some(trigger)
case EventD(trigger) => trigger
case _ => None
}
def handleSomeTypeOfEvent(maybeTrigger: Option[Trigger]): String = ???
val ev: Event = ???
handleSomeTypeOfEvent(extractTrigger(ev))