Scala 检查 ListBuffer[MyType] 是否包含一个元素

Scala check if a ListBuffer[MyType] contains one element

我有两个class:

class Item(val description: String, val id: String) 

class ItemList {
  private var items : ListBuffer[Item] = ListBuffer()
}

如何检查项目是否包含 description=x 和 id=y 的项目?

那就是

list.exists(item => item.description == x && item.id == y)

如果您还为您的 class 实现了 equals(或者更好,使其成为自动执行的 case class),您可以将其简化为

case class Item(description: String, id: String)
 // automatically everything a val, 
 // you get equals(), hashCode(), toString(), copy() for free
 // you don't need to say "new" to make instances

list.contains(Item(x,y))

像这样:

def containsIdAndDescription(id: String, description: String) = {
   items.exists(item => item.id == id && item.description == description )
}

也许想到这些方法,还有:

//filter will return all elements which obey to filter condition

list.filter(item => item.description == x && item.id == y)

//find will return the fist element in the list

list.find(item => item.description == x && item.id == y)