我想在Scala中使用以下规范实现元素集合:
Set[A]
)和"存档" part(a Set[UUID]
)archivable: A => Boolean
只要活动元素在更新之前无法存档,这是一个相对较好的暂定实现。
class ItemsCollection[A](archivable: A => Boolean)(private val _active: Map[UUID, A], private val _archived: Set[UUID]) {
private def this(items: Iterable[A] = Seq.empty[A]) = this(items filterNot archiveable map (t => (t.id -> t)) toMap, items filter archiveable map (_.id) toSet)
def active = _active.values
def archived = _archived
def +(item: A): ItemsCollection =
if(archivable(item)) {
new ItemsCollection(_active - item.id, _archived + item.id)
} else {
new ItemsCollection(_active + (item.id -> item), _archived)
}
}
适用于:
def archivedByPriority(item: A): Boolean = item.priority == Low
不会合作:
def archivedByTimestamp(item: A): Boolean = item.timestamp + 1.hour < DateTime.now()
我也非常乐意接受有关这是否是实现此类集合的正确方法的反馈,以及在Scala中是否有更为惯用的方法。