coder25
coder25

Reputation: 2393

Using Try[Boolean] with list iteration

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)

The above works but when I change method to below

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

The below line gives compile error as it expects a boolean

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

I want the handling of success and failure be outside isValidDate method

Upvotes: 2

Views: 97

Answers (2)

Tim
Tim

Reputation: 27356

If you want to handle the exception outside isValidDate then there is no point in changing isValidDate, you can simply catch the exception outside. For example

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

This will fail the whole test if there is an exception. If you want to ignore exceptions and keep testing later employees, do this

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

However in this case I believe that it better to put the exception handling in isValidDate, even though this is not what you say you want:

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

Upvotes: 1

hasumedic
hasumedic

Reputation: 2167

First of all, you'll need to change the implementation of isValidDate:

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

Then, the implementation of your higher order function would need to deal with the Try:

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

Or as Zang proposes in the comments:

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

I would say though, that I'm not sure all this is necessary. Does isAfter throw any exception? Try is mostly used to capture exceptional code, which I don't think is the case here.

Upvotes: 1

Related Questions