scala - 如何在 Scala Seq 中移动项目?
问题描述
假设我有一个这样的案例类:
case class Card(id: UUID, title: String)
和这样的 Bucket 类:
case class Bucket(id: UUID, title: String, cards: Seq[Card]) {
def moveCard(cardId: UUID, newIndex: Int): Bucket =
copy(cards = {
???
})
}
我将如何填写 moveCard() 方法以找到给定的卡片并将其移动到序列中的新索引?
解决方案
您可以使用双倍剂量patch()
将项目移动到新位置。不幸的是,根据方向,前进或后退,它会有所不同。
case class Bucket(id: UUID, title: String, cards: Seq[Card]) {
def moveCard(cardId: UUID, newIndex: Int): Bucket = {
val from = cards.indexWhere(_.id == cardId)
if (from < 0) throw new Error("no such card")
copy(cards =
if (from < newIndex)
cards.patch(newIndex+1,Seq(cards(from)),0).patch(from,Seq(),1)
else
cards.patch(newIndex,Seq(cards(from)),0).patch(from+1,Seq(),1)
)
}
}
或者@LeoC 提供的这个非常好的简化:
copy(cards = cards.patch(from, Seq(), 1).patch(newIndex, Seq(cards(from)), 0))
推荐阅读
- python - 尝试一次通过搜索发送一个列表项
- python - 如何识别单个列中的不同数据类型?
- html - 将选择元素的选项值作为记录的 id (HTML) 是一种好习惯吗?
- javascript - 如何使用 React Native Navigation (v5) 向父页面发送数据?
- git - Git过滤选项卡到空间转换但不显示文件已修改
- python - python中的git命令,无法识别有效的git
- excel - 识别列中前一个单元格值仅在可见范围内不同的行号
- csv - .CSV 文件是否由 Spark 并行分解和处理
- ios - 添加子视图后UIButton无法点击
- javascript - 如何在js中访问id样式的属性