首页 > 解决方案 > 如何在 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() 方法以找到给定的卡片并将其移动到序列中的新索引?

标签: scalafunctional-programming

解决方案


您可以使用双倍剂量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))

推荐阅读