scalalistbuffer

Scala check if a ListBuffer[MyType] contains one element


I have two class:

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

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

How can I check if items contain one item with description=x and id=y?


Solution

  • That would be

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

    If you also implement equals for your class (or even better, make it a case class which does that automatically), you can simplify that to

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