Recently I found myself writing either DB queries or simple Seq method chains which I would like to be dynamic based on user input, for instance:
def between(from: Option[DateTime], to: Option[DateTime]): Seq[MyObject] = { db.all() // let's say this returns Seq[MyObject] /* Here I want to either restrict the upper/lower bounds with from/to if they exist or take all the values otherwise */ } If I were lazy I'd just go with:
def between(from: Option[DateTime], to: Option[DateTime]): Seq[MyObject] = { if(from.isEmpty && to.isEmpty) db.all() else if(from.isEmpty) db.all().filter(_.date <= to.get) else if(to.isEmpty) db.all().filter(_.date >= from.get) else db.all().filter(_.date >= from.get && _.date <= to.get) } Obviously filter is just an example, I have the same problem with for instance take when I want to take n elements or all based on Option.
But what if I have more Options passed? What would be the idiomatic way of doing this in Scala?
I can go with pattern matching, but that's not extremely different to if/else?
I could make several vals and do from.map(...).getOrElse() but that introduces temporary vals and again doesn't look that much better than if/else.
Are there any other tricks I could use?
between(None, Some(...)orbetween(None, None)? I don't think it has any obvious semantic and I don't know what I should expect to be returned as a user, so I wonder if this method makes sense at allbetween(None, None)will return all the objects,between(None, Some(to))will only put an upper bound, so all the objects that are older thento.