First, never use var
in Scala (unless you have to). Better use val
.
var filter = availableRestaurants.filter(_ => commonOrder.contains(_.cuisine))
This is given the filter
function an anonymous function which discards its first argument. But you want to use the argument for the contains check. (the _
in a function call is special, the second one does not refer to the first)
The reason for the error is that the commonOrder.contains(_.cuisine)
part needs to be (eta) expanded first, ie. the method call needs to be converted to a function since filter
expects a function. But without knowing what _
stands for, and hence what the type of _.cuisine
is, this fails.
Do it like this:
val filter = availableRestaurants.filter(r => commonOrder.contains(r.cuisine))
Or, expand the method into a function manually beforehand:
val containsCuisine = (r: Restaurant) => commonOrder.contains(r.cuisine)
val filter = availableRestaurants.filter(containsCuisine)
Or, to use composition, similar to what you can do with lenses:
val cuisineOf = (r: Restaurant) => r.cuisine // re-usable
val filter = availableRestaurants.filter(cuisineOf andThen commonOrder.contains)