0

If I wanted to pattern match on a basic option type in Scala, I would run something along the lines of

val opt = Option(5)
val lessThanTen = opt match {
    case Some(e) => if (e < 10) true else false
    case None => None
}

But suppose that opt comes as a result of one of Slick's Queries, and therefore has the Lifted Embedding Type of Rep[Option[Int]] How can I carry out the same pattern matching in a way that allows us the to see inside of the the lifted type? I.e. something along the lines of

val opt = Rep(Option(5))
val lessThanTen = opt match {
    case Rep[Some(e)] => Rep[if (e < 10) true else false]
    case Rep[None] => Rep[None]
}

But of course, one that compiles ;)

Elie Bergman
  • 121
  • 4

1 Answers1

1

You can use the map method to apply some operation on the content of a Rep.

val rep: Rep[Option[Int]] = ???
val boolRep = rep.map {
    case Some(i) => Some(i < 10)
    case None => None
}

Even better: Option, like many other collection types in Scala, also has a similar map method, so you can write

val boolRep = rep.map(_.map(_ < 10))

In that expression, the first _ is the Option[Int], and the second one is the Int itself. In cases where the Option[Int] is None, the map method has nothing to apply the given function to, so it returns None by definition.

francoisr
  • 4,407
  • 1
  • 28
  • 48
  • The Rep type doesn't actually have a 'map' function defined on it. This solution unfortunately does not work. val rep: Rep[Option[Int]] = Some(3) val boolRep = rep.map(_.map(_ < 10)) does not compile – Elie Bergman Oct 09 '19 at 14:41
  • You're right, I answered too fast. Can you describe what you are really trying to achieve rather than the subproblem you think you need to solve? I mean, in terms of database query, what do you want to do? – francoisr Oct 10 '19 at 07:42