This is a kind of cosmetic Scala question. A list with objects needs to be filtered on the objects' attributes. I need to report if the first check on the attribute results in an empty list. Simplified code:
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)}")
Of course I can split up the filter statements and check the intermediate result but I was hoping I could do it more scala way.. I thought something like.
list.filter(_.id == focusId)
match { case List() => { println "error"; List()}
case _ => _}
But that doesn't work. Is there a functional (or fluent) way to implement the desired behaviour?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…