【发布时间】:2018-09-07 19:50:48
【问题描述】:
大家!
我对 Scala 模式匹配有一点问题。我正在为我的 Web 应用程序使用 Korolev 框架,但我敢打赌,问题在 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方式正确地做到这一点?谢谢你。
【问题讨论】: