1

我有两个班级:

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

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

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

4

3 回答 3

4

那将是

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

如果您还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))
于 2019-05-24T08:53:02.473 回答
1

像这样的东西:

def containsIdAndDescription(id: String, description: String) = {
   items.exists(item => item.id == id && item.description == description )
}
于 2019-05-24T08:53:47.570 回答
0

也许还可以考虑这些方法:

//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) 
于 2019-05-25T18:21:46.420 回答