这是一种美容斯卡拉问题。对象列表需要根据对象的属性进行过滤。如果对属性的第一次检查导致列表为空,我需要报告。简化代码:过滤器和报告多谓词
case class Account (id: Int, balance: Float)
def doFilter(list: List[Account], focusId: Int, thresHold: Float): List[Account] = {
list.filter(_.id == focusId)
// ## if at this point if the list is empty, an error log is required.
.filter(_.balance >= thresHold)
}
var accounts = List(Account(1, 5.0f), Account(2, -1.0f), Account(3, 10f), Account(4, 12f))
println(s"result ${doFilter(accounts, 1, 0f)}")
我当然可以拆分过滤语句,检查中间结果,但我希望我能做到这一点更斯卡拉方式..我想是这样。
list.filter(_.id == focusId)
match { case List() => { println "error"; List()}
case _ => _}
但这并不奏效。是否有功能(或流利)的方式来实现所需的行为?