如何获得符合特定条件的列表中的项目?

时间:2014-12-06 20:24:56

标签: scala pattern-matching scala-collections predicate

我有以下示例代码:

package models

import java.util.concurrent.atomic.AtomicInteger
import scala.collection.mutable.ArrayBuffer

case class Task(id: Int, label: String)

object Task {

  private val buffer = new ArrayBuffer[Task]
  private val incrementer = new AtomicInteger()

  def all(): List[Task] = buffer.toList

  def create(label: String): Int = {
    val newId = incrementer.incrementAndGet()
    buffer += new Task(newId, label)
    newId
  }

  def delete(id: Int): Boolean = {

    // TODO : add code

  }
}

在方法delete中,我需要找到一个Task id等于参数id,如果找到一个,我需要将其从集合中移除从方法返回true。否则(如果没有找到)我应该返回false。

我知道如何用C#或Java等命令式语言执行此操作,但Scala让我感到困惑。

PS:代码严格用于理解语言和平台,在生产中推得太多。别担心。

1 个答案:

答案 0 :(得分:2)

这是一种可能的解决方案,但在这种情况下,我认为也可以切换到var + immutable ArrayBuffer并使用filter。另请注意,此代码不是线程安全的

  import java.util.concurrent.atomic.AtomicInteger
  import scala.collection.mutable.ArrayBuffer

  case class Task(id: Int, label: String)

  object Task {

    private val buffer = new ArrayBuffer[Task]
    private val incrementer = new AtomicInteger()

    def all(): List[Task] = buffer.toList

    def create(label: String): Int = {
      val newId = incrementer.incrementAndGet()
      buffer.append(Task(newId, label))
      newId
    }

    def delete(id: Int): Boolean = {
      buffer.
        find(_.id == id). // find task by id
        map(buffer -= _). // remove it from buffer
        exists(_ => true) // the same as: map(_ => true).getOrElse(false) 
    }
  }

  val id1 = Task.create("aaa")
  val id2 = Task.create("bbb")

  println(s"Id1 = $id1 Id2 = $id2")
  println(s"All = ${Task.all()}")

  val deleted = Task.delete(id1)
  println(s"Deleted = $deleted")
  println(s"All = ${Task.all()}")


  println(s"Not Deleted = ${Task.delete(123)}")