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 随机数生成器不生成范围之间的唯一随机数

scala - Scala 中的大小参数化

java - 使用模式匹配从文件中排序,Java

haskell - 如何对列表中的一对元素求和?

scala - 使用 @switch 优化 Java 枚举的 Scala 模式匹配

java - 使用java,在字符串中查找单词的方法有哪些?

Scala:链接多个 Option.when 调用

scala - Akka HTTP 在 docker 容器中过早关闭

json - 使用 circe 将 Scala None 编码为 JSON 值

java - 正则表达式允许 1.00、.10 或 10。但不允许单个小数