如何模式匹配大型

如何模式匹配大型

本文介绍了如何模式匹配大型 Scala 案例类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下 Scala 案例类:

Consider the following Scala case class:

case class WideLoad(a: String, b: Int, c: Float, d: ActorRef, e: Date)

模式匹配允许我提取一个字段并丢弃其他字段,如下所示:

Pattern matching allows me to extract one field and discard others, like so:

someVal match {
    case WideLoad(_, _, _, d, _) => d ! SomeMessage(...)
}

我想要做的,以及当案例类有大约 20 个奇数字段时更相关的是,以不涉及输入 WideLoad(_, _, _, _, _, some, _, _, _, thing, _, _, 有趣).

What I would like to do, and what's more relevant when a case class has ~20 odd fields, is to extract only a few values in a way that does not involve typing out WideLoad(_, _, _, _, _, some, _, _, _, thing, _, _, interesting).

我希望命名的 args 可以在这里提供帮助,尽管以下语法不起作用:

I was hoping that named args could help here, although the following syntax doesn't work:

someVal match {
    case WideLoad(d = dActor) => dActor ! SomeMessage(...)
    //              ^---------- does not compile
}

这里有什么希望,还是我一直在输入很多很多_, _, _, _?

Is there any hope here, or am I stuck typing out many, many _, _, _, _?

编辑:我知道我可以做 case wl @ WideLoad(...whatever...) =>wl.d,但我仍然想知道是否有更简洁的语法可以满足我的需要而无需引入额外的 val.

EDIT: I understand that I can do case wl @ WideLoad(...whatever...) => wl.d, yet I'm still wondering whether there's even terser syntax that does what I need without having to introduce an extra val.

推荐答案

我不知道这是否合适,但您也可以构建一个对象来匹配该字段或该组字段(未经测试的代码):

I don't know if this is appropriate, but you can also build an object just to match that field, or that set of fields (untested code):

object WideLoadActorRef {
  def unapply(wl: WideLoad): Option[ActorRef] = { Some(wl.d) }
}

someVal match {
  case WideLoadActorRef(d) => d ! someMessage
}

甚至

object WideLoadBnD {
  def unapplySeq(wl: WideLoad): Option[(Int,ActorRef)] = { Some((wl.b,wl.d)) }
}

someVal match {
  case WideLoadBnD(b, d) => d ! SomeMessage(b)
}

这篇关于如何模式匹配大型 Scala 案例类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 03:22