Mapping with a function that returns Try[T] to return a Try[T] instead a List[Try[T]]
![Creative The name of the picture](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgKPz5qhCkKGdpPJ0wkSm5JqlliSJoZg92-H4DuCruovhkVFuXerCphZt9wys_Gr3uwQyXObMHDwattjG5BSeCEl_LdDq1GPLct8qYyRyX4fZ9C93oW-TX7IGZLYDwqRgfFCXA4aUxkBAcS/s1600/1.jpg)
![Creative The name of the picture](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh6VebLk98DYwS3K2nWZSCatab-q4HrSuRk91M4fQA8SHrKU_-x-lq1n780pSU_bIVLqMRv6pc3dhhh-Y2PUwBS9mM0BxvY1eM6XsM-e7Diu4z-wAoeDG0vB3-2_1U9RE8sO0lg4PHiIXbI/s400/Clash+Royale+CLAN+TAG%2523URR8PPP.png)
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