Itachi
Itachi

Reputation: 1433

Mapping values from a List of Either to List

I have two lists one is:

val l1 = List[Either[A,B]]

and

val l2 = List[String]

Now, all I need to do is map these two. i.e., if l1 is A then return corresponding value from l2. Tried something like:

for {
   elem1  <- l1
   elem2  <- l2
   result <- if(elem1.isLeft) url
} yield result

This doesn't work. Because, I am not handling the else case. Similarly with match instead of if. How do I go about to achieve this?

Upvotes: 1

Views: 384

Answers (1)

nicodp
nicodp

Reputation: 2392

You could do something like this (I'm assuming l2 has at least the same number of elements of type A as Lefts in l1):

val result: List[String] = l1.zip(l2).filter(_._1.isLeft).map(_._2)

Otherwise, if you prefer using for, this will also do the trick:

scala> for {
 |   e1 <- l1.zip(l2)
 |   if e1._1.isLeft
 | } yield e1._2

Upvotes: 1

Related Questions