2017-01-23 142 views
1

这是一种美容斯卡拉问题。对象列表需要根据对象的属性进行过滤。如果对属性的第一次检查导致列表为空,我需要报告。简化代码:过滤器和报告多谓词

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 _ => _} 

但这并不奏效。是否有功能(或流利)的方式来实现所需的行为?

回答

2

下面的代码是从轻微的修改this SO answer from Rex Kerr

implicit class KestrelPattern[A](private val repr: A) extends AnyVal { 
    def tee[B](f: A => B) = { f(repr); repr } // B is thrown away (Unit) 
} 

他称之为tap。我选择了tee,因为它与unix tee命令相似。

用法:

scala> List[Int](3,5,7).tee{x => if (x.isEmpty) println("ERROR")}.sum 
res42: Int = 15 

scala> List[Int]().tee{x => if (x.isEmpty) println("ERROR")}.sum 
ERROR 
res43: Int = 0 
2

如果您需要一次,那么记录中间结果可能是最简单的方法。如果您需要这在几个地方,你可以使代码更好一点使用扩展方法:

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 
    } 
} 

然后你可以使用它像这样:

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

配套工程的模式,你的代码的错误来自于事实,你正试图在第二种情况下返回_,你可能要检查herehere为什么这个可能是一个问题:

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()