Search code examples
scalaslick

Pass in custom predicate to TableQuery's filter method


I am trying to generalize a function to filter out some TableQuery in slick using filter, so I have created the following method:

def fetchCoffee(coffe: String)(p: MyTable => Boolean) =
    // ...
    myTableQuery.filter(p)
    // ...

and I called it like this:

fetchCoffee("micoffee")(_.coffeeId == id)

But it is failing with this error:

Error:(43, 29) inferred type arguments [Boolean] do not conform to method filter's type parameter bounds [T <: slick.lifted.Rep[_]]
    val query = MyTable.filter(p)
Error:(43, 36) type mismatch;
 found   : MyTable => Boolean
 required: MyTable => T
    val query = myTableQuery.filter(p)
Error:(43, 35) Type T cannot be a query condition (only Boolean, Rep[Boolean] and Rep[Option[Boolean]] are allowed
    val query = myTableQuery.filter(p)

I have tried to change p's type to p: MyTable => Rep[Boolean], and Rep[MyTable => Boolean] but still not working. I have also tried to pass in the ExecutionContext as implicit to fetchCoffee without luck.

How should I write the predicate type to conform with the type bound T?


Solution

  • Try to use Rep[Boolean] instead of Boolean and === instead of ==.

    def fetchCoffee(coffe: String)(p: MyTable => Rep[Boolean]) = {
      myTableQuery.filter(p)
    }
    
    fetchCoffee("micoffee")(_.coffeeId === id)