filter and report multiple predicates

后端 未结 3 1238
长发绾君心
长发绾君心 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条回答
  •  -上瘾入骨i
    2020-12-21 21:58

    The pattern matching works, the error of your code comes from the fact that you are trying to return _ in the second case, you may want to check here and here for why this could be a problem:

    accounts.filter(_.id == 1) match {
           case List() => { println("error"); List() }
           case x => x.filter(_.balance > 1.0)
    }
    // res19: List[Account] = List(Account(1,5.0))
    
    
    accounts.filter(_.id == 5) match {
           case List() => { println("error"); List() }
           case x => x.filter(_.balance > 1.0)
    }
    // error
    // res20: List[Account] = List()
    

提交回复
热议问题