是否有更优雅的方法基于可选参数值来过滤列表?

def f(dates: List[Date], start: Option[Long], end: Option[Long]): List[Date] = {
    (start, end) match {
        case (Some(s), Some(e)) =>  dates filter (_.getTime > s) filter (_.getTime < e)
        case (Some(s), None) => dates filter (_.getTime > s)
        case (None, Some(e)) => dates filter (_.getTime < e)
        case (None, None) => dates
    }
}

使用三个可选参数值,将有9种情况,以此类推。

最佳答案

一种方法如下:

def f(dates: List[Date], start: Option[Long], end: Option[Long]): List[Date] =
  dates.filter( d => start.map(d.getTime > _).getOrElse(true) )
       .filter( d => end.map(d.getTime < _).getOrElse(true) )

或者,更简洁地说,您可以在选项上使用forall:
def f(dates: List[Date], start: Option[Long], end: Option[Long]): List[Date] =
  dates.filter( d => start.forall(d.getTime > _) )
       .filter( d => end.forall(d.getTime < _) )

关于scala - 根据可选参数值过滤列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19518440/

10-13 05:28