Let's say I have a case class like this:
case class Card(id: UUID, title: String)
and a Bucket class like this:
case class Bucket(id: UUID, title: String, cards: Seq[Card]) {
def moveCard(cardId: UUID, newIndex: Int): Bucket =
copy(cards = {
???
})
}
How would I fill in the moveCard() method to find the given card and move it to the new index in the sequence?
You can use a double dose of patch()
to move an item to a new location. Unfortunately it's a little different depending on the direction, forward or back.
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)
)
}
}
Or this very nice simplification offered by @LeoC:
copy(cards = cards.patch(from, Seq(), 1).patch(newIndex, Seq(cards(from)), 0))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.