1
votes

Missing parameter type for expanded function

So my code is :

var filter = availableRestaurants.filter(_ => commonOrder.contains(_.cuisine))

this is throwing an error called missing parameter type for expanded function at "_.cuisine". I also tried:

var filter = availableRestaurants.filter(commonOrder.contains(_.cuisine))

commonOrder is a list of strings and availableRestaurants is a list of objects that contains a string field called cuisine What would be the best way to rewrite something like this or is this completely illogical?

1

1 Answers

2
votes

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)