Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

scala - filter and report multiple predicates

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you need it once, then logging an intermediate result is, probably, the simplest way. If you need this at several places, you can make the code a bit nicer using extension methods:

implicit class ListOps[+A](val list: List[A]) extends AnyVal {
    def logIfEmpty(): List[A] = {
      if (list.isEmpty) {
      println("Error: empty list") 
      // or whatever; you can even pass it as an argument
    }
    list
  }
}

Then you can use it like this:

def doFilter(list: List[Account], focusId: Int, thresHold: Float): List[Account] = list
  .filter(_.id == focusId)
  .logIfEmpty()
  .filter(_.balance >= thresHold)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...