如何在Scala Seq中移动项目?

时间:2019-01-08 21:18:00

标签: scala functional-programming

假设我有一个这样的案例类:

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()方法以找到给定的卡并将其移动到序列中的新索引?

1 个答案:

答案 0 :(得分:2)

您可以使用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))