Mapping with a function that returns Try[T] to return a Try[T] instead a List[Try[T]]
Mapping with a function that returns Try[T] to return a Try[T] instead a List[Try[T]]
The title of this question is a tad weird but I want to accomplish is as follows.
I have a List
of Tasks
. For the sake of convenience the task is defined as follows:
List
Tasks
case class Task(name: String)
I have a TaskStorage
trait with a store method that will persist the task and return a Try[Task]
.
TaskStorage
Try[Task]
My storage doesn't have a batch storage API so I need to mimic batch storage in the application end. The way I was initially doing was as follows:
val tasks = List(task1, task2)
tasks.map(taskStorage) -> This returns a List[Try[Task]]
My API design might be a little suspect here but what I want is some thing as follows:
def batchStoreTasks(tasks: List[Task]):Try[Task] =
//
The Try[Task]
indicates the last task that was successfully persisted by the storage. Since I was unable to find an idiomatic way to accomplish the above, I resorted to pattern match and did the following:
Try[Task]
def batchStoreTasks(tasks: List[Task]): Try[Task] = tasks match
case Nil => Failure(EmptyTaskListException)
case x :: Nil => taskStorage(x)
case x :: t => val storedTask = taskStorage(x); if(storedTask.isSuccess) batchStoreTasks(t) else storedTask
I am able to get the job done but I am missing the idiomatic way to accomplish the above. It will be great if I could be pointed in the right direction to restructure the batchStoreTasks to give it a more idiomatic shape.
Thanks
1 Answer
1
Assuming that you want to return the failure of the last task if the list was non-empty but all tasks failed:
val tryTasks = tasks.map(taskStorage).reverse
tryTasks
.find(_.isSuccess) // try to find a success
.orElse(tryTasks.headOption) // return last failure
.getOrElse(Failure(EmptyTaskListException)) // special failure for empty list
Note that it will usually throw away the failure information captured in the failed tasks, but that's what I understood from your description.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Comments
Post a Comment