首页 > 解决方案 > Scala 检查 ListBuffer[MyType] 是否包含一个元素

问题描述

我有两个班级:

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

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

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

标签: scalalistbuffer

解决方案


那将是

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))

推荐阅读