Reputation: 36008
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
Upvotes: 6
Views: 84
Reputation: 6220
You could do something like this:
val a = List(1,2,3,4,5)
a.find(_ == 0)
This way, if the filter operation results in an empty list, you will have a None.
In your specific example:
myList1.find(_.id == toFind1.id)
Now you have several options to continue with the operation:
myList1.find(_.id == toFind1.id).getOrElse("DefaultValue")
myList1.find(_.id == toFind1.id).map(somFunc)
etc.Hope it helps.
Upvotes: 0
Reputation: 61774
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)
Upvotes: 5