I have a list of a case class. I want to get a particular item from the list.
I do
myList.filter(_.id == myobject.id)(0)
This would work when the filter
actually returns something. But when filter doesn't return anything I get an index out of bound exception.
scala> case class Color (id: Int, name: String)
defined class Color
scala> val myList1 = List[Color](Color(1, "red"), Color(2, "green"), Color(3, "blue"))
myList1: List[Color] = List(Color(1,red), Color(2,green), Color(3,blue))
scala> val toFind1 = Color(10, "white")
toFind1: Color = Color(10,white)
scala> myList1.filter(_.id == toFind1.id)(0)
java.lang.IndexOutOfBoundsException: 0
You could return an Option[Color]
in order to gracefully handle items that can't be found.
In that case, I'd suggest using the find
method as such:
// val colors = List[Color](Color(1, "red"), Color(2, "green"), Color(3, "blue"))
colors.find(_.id == 2)
// Some(Color(2,green))
colors.find(_.id == 5)
// None
If you'd rather return a Color
rather than an Option[Color]
you can always return a default value in case you can't find the Color
in question:
colors.find(_.id == 5).getOrElse(Color(7, "purple"))
// Color(7,purple)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With