使用Try [Boolean]进行列表迭代

时间:2019-01-08 10:46:23

标签: scala

case class Employee(name :String, dept :String, empId:String, startDate:String)
val emp1 = Employee("abc","accounts", "1234","2019-09-28")
val emp2 = Employee("def","HR", "12345","2019-09-29")
val emp3 = Employee("pp","HR", "12346", "2019-09-28")
val emp4 = Employee("xyz","accounts", "12347","2019-09-20")

val list = Seq(emp1, emp2, emp3, emp4)

def isValidDate(date: LocalDateTime, e: 
   Employee):Boolean={
     date.isAfter(e.startDate)
    }

private def test(name :String, date:String,list:Seq[Employee])={

  list.exists(e =>isValidDate(LocalDate.parse(date).atStartOfDay(), e))
}

test("abc",2019-09-28, list)
test("xyz",2019-09-28, list)
test("def",2019-09-28, list)

以上方法有效,但是当我将方法更改为以下方法

def isValidDate(date: LocalDateTime, e: 
   Employee):Try[Boolean]={
     date.isAfter(e.startDate)
    }

下面的代码行会产生编译错误,因为它期望一个布尔值

  list.exists(e =>isValidDate(date, e))

我希望对成功和失败的处理不在isValidDate方法之外

2 个答案:

答案 0 :(得分:1)

首先,您需要更改isValidDate的实现:

def isValidDate(date: LocalDateTime, e: Employee): Try[Boolean]={
  Try { date.isAfter(e.startDate) }
}

然后,您的高阶函数的实现将需要处理Try

private def test(name: String, date: LocalDateTime, list: Seq[Employee]) = {
  list.exists(isValidDate(date, _) match {
    case Failure(_) => false
    case Success(value: Boolean) => value
  })
}

或者如Zang在评论中建议的那样:

private def test(name: String, date: LocalDateTime, list: Seq[Employee]) = {
  list.exists(isValidDate(date, _).getOrElse(false))
}

我会说,我不确定这一切是否必要。 isAfter是否抛出任何异常? try主要用于捕获 exception 代码,我认为这里不是这种情况。

答案 1 :(得分:1)

如果您想在isValidDate之外处理异常,那么更改isValidDate毫无意义,您只需在外部捕获异常即可。例如

private def test(name: String, date: LocalDateTime, list: Seq[Employee]) =
  Try {
    list.exists(e => isValidDate(date, e))
  }.getOrElse(false)

如果有异常,这将使整个测试失败。如果您想忽略异常并继续测试以后的员工,请执行此操作

private def test(name: String, date: LocalDateTime, list: Seq[Employee]) =
  list.exists(e => Try(isValidDate(date, e)).getOrElse(false))

但是在这种情况下,我认为最好将异常处理放入isValidDate中,即使这不是您想要的内容:

def isValidDate(date: LocalDateTime, e: Employee): Boolean =
  Try(date.isAfter(e.startDate)).getOrElse(false)

private def test(name: String, date: LocalDateTime, list: Seq[Employee]) =
  list.exists(e => isValidDate(date, e))