在scala中使用布尔值尝试[Boolean]

时间:2019-01-10 14:40:29

标签: 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(LocalDate.parse(e.startDate).atStartOfDay())
}

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

  list.exists(e =>isValidName(name, 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)

更改为以下代码会导致错误Boolean && Try [Boolean]不能一起使用,而是删除isValidName使其可以正常工作

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

list.exists{e =>isValidName(name, e)&&isValidDate(LocalDate.parse(date).atStartOfDay(), e) match{
  case Success(x)=> x
  case Failure(ex) => throw ex
}}
}

1 个答案:

答案 0 :(得分:0)

可以用Try如下包装。.

def validateDate(e:Employee) = Try {
  isValidDate(LocalDate.parse(date).atStartOfDay(), e)
} match {
  case Success(x) => x

  case Failure(ex) => 
    //handle failure the way you want
    throw ex
}

list.exists(e => isValidName(name, e) && validateDate(e))

或者你可以做。.

list.exists(e => isValidName(name, e) && Try(isValidDate(LocalDate.parse(date).atStartOfDay(), e)).getOrElse(false))