filter and report multiple predicates

后端 未结 3 1241
长发绾君心
长发绾君心 2020-12-21 20:54

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

3条回答
  •  悲哀的现实
    2020-12-21 21:42

    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)
    

提交回复
热议问题