Reputation: 3246
I have a method which return Future[List[Employee]]
. I want to check the list size for various purpose. I am not able to call size
on list and I think its because its in Future
. Any suggestion?
val employees: Future[List[Employee]] = companyService.findEmployeesWorkingOn(someDate)
employees match {
case emp if(emp.size == 1) => Logger.info("Only one employee working")
case emp if(emp.size == 0) => Logger.info("No one working")
case _ => Logger.info("Multiple employees working")
}
Upvotes: 3
Views: 1261
Reputation: 26579
No need to check the size for your use case:
val employees: Future[List[Employee]] = …
val result = employees map {
case Nil => "no employees"
case List(e) => "one employee"
case es => "multiple employees"
}
Upvotes: 0
Reputation: 20415
Use a for comprehension which desugars to a flatMap
,
for ( e <- employees ) yield e.size match {...}
Here list e
is matched only if the future succeeds.
Upvotes: 0
Reputation: 23329
You need to "wait" for the future to happen or not. You can use map
to map the Future[List[Employee]]
to a Future[Int]
and use the onSuccess
callback.
val sizeFuture = employees.map(_.size) // returns a Future[Int]
sizeFuture onSuccess {
case size:Int => println(size) // do your stuff here
}
Upvotes: 3