scalamonix

Task[List[List[A]]] to Task[A] if list has elements


I have a method which returns Task[List[List[A]]] and I need to transform to Task[A] if the list is greater than 0

def method():Task[List[List[A]]] = {}

val d:Task[List[A]] = method().map(_.flatten)

How to get Task[A] is a list of A if the inner method has more than 0 elements

I am able to convert to Task[List[A]] as you can see above


Solution

  • You're flattening the List[List[A]] into a List[A] in the intuitive way, all wrapped in a Task. If you provide the method to go from a List[A] to an A (edit: see below), then you can call it from a map on the task as follows.

    def method():Task[List[List[A]]] = {}
    
    def listToItem(list: List[A]): A = ???
    
    def d: Task[A] = method().map(_.flatten).map(listToItem(_))
    

    You say that you want listToItem to take the first element of the list. Unfortunately, such a function wouldn't know what to do if the list were empty. You could use list.head, which will throw an exception if the list is empty, or you could use list.headOption, which will return an Option[T] rather than T.