我有两个班级:
class Item(val description: String, val id: String)
class ItemList {
private var items : ListBuffer[Item] = ListBuffer()
}
如何检查项目是否包含一项 description=x 和 id=y 的项目?
我有两个班级:
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)
如果您还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)