scala - 从相同特征派生的案例类的模式匹配

标签 scala pattern-matching

大家好!

我在使用 Scala 模式匹配时遇到了一点问题。我正在使用 Korolev我的 Web 应用程序的框架,但我敢打赌,问题在 Scala 中更深层次。

我有一个适用于所有状态的基本特征:

trait BaseState {
  val notifications: List[Notification]
}

和两个派生案例类:

case class GuestState(
                       notifications: List[Notification] = List(),
                       isRegistration: Boolean = false
                     ) extends BaseState

case class AuthenticatedState(
                          notifications: List[Notification] = List(),
                          user: UserWithPermissions
                        ) extends BaseState

在其中一个事件处理程序中,我需要在没有特定通知的情况下获得类似的状态。现在它是这样工作的:

event('click) { access =>
              access.transition {
                case s: GuestState => s.copy(notifications = notifications.filter(x => x != n))
                case s: AuthenticatedState => s.copy(notifications = notifications.filter(x => x != n))
              }
          }

对于这两种类型,我必须做完全相同的事情来复制代码,因为 BaseState 没有 copy() 方法并且编译器因错误而失败。

我怎样才能在 scala-way 中正确地做到这一点?谢谢。

最佳答案

这两种情况实际上并没有做同样的事情,因为这两个copy方法有不同的签名。因此,虽然文本可能相同,但代码实际上在每种情况下都在做一些不同的事情。

这里的一个选项是向特征添加一个抽象的filterNotifications 方法并调用它:

trait BaseState {
  val notifications: List[Notification]
  def filterNotifications(f: Notification => Boolean): BaseState
}

case class GuestState(
  notifications: List[Notification] = List(),
  isRegistration: Boolean = false
) extends BaseState {
  def filterNotifications(f: Notification => Boolean): BaseState =
    this.copy(notifications=notifications.filter(f))
}

case class AuthenticatedState(
  notifications: List[Notification] = List(),
  user: UserWithPermissions
) extends BaseState {
  def filterNotifications(f: Notification => Boolean): BaseState =
    this.copy(notifications=notifications.filter(f))
}

关于scala - 从相同特征派生的案例类的模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52221098/

相关文章:

Scala 案例有 22 个字段,但在 Scala 2.11.5 中存在 play-json 问题

scala - 使用 Slick 3 的动态排序

Scala Stdin.readLine() 似乎没有按预期工作

sql - 顺序扫描以 varchar_pattern_ops 索引的列

java - MySQL 重复事件

Android:过滤特定 Uri 模式的 Intent

scala - 在 build.sbt 中编写 SBT 任务时,如何使用我的库依赖项?

java - 无法使用 Scala 和 Spring MVC 3 返回 JSON

Java正则表达式问题

haskell - 测量二叉树大小的函数