St.Antario
St.Antario

Reputation: 27375

Replace flatMap/map chain with for-comprehension

I'm trying to use for-comprehension for the following:

val s: Seq[Option[Int]] = //...
val t: Option[Int] = //...

s.map(sv => t.flatMap(tv => sv.map(_ == tv))) 

I tried this:

val r: Seq[Option[Boolean]] = for(
  sv <- s;
  tv <- t;
  svv <- sv
) yield svv == tv //Seq[Boolean] does not conform to Seq[Option[Boolean]]

Is there a way to write in concisely with for-comprehension?

Upvotes: 4

Views: 1992

Answers (2)

slouc
slouc

Reputation: 9698

Using different collections (hard to resist using the M-word here) within the same for-comprehension is discouraged anyways, and it won't work in general case. Sequence of options will work only because Scala defines some implicit conversions for such situations (since they are quite common).

You are much better off using two separate for comprehensions, one for the sequence, and the other one for option.

val s: Seq[Option[Int]] = List(Some(1), None, Some(2))
val t: Option[Int] = Some(2)

val result = for {
  elem <- s
} yield for {
  evalue <- elem
  tvalue <- t
} yield evalue == tvalue

println(result) // List(Some(false), None, Some(true))

Upvotes: 10

tkachuko
tkachuko

Reputation: 1986

I would probably mix things to keep it simple and short:

val r: Seq[Option[Boolean]] =
  for (
    opt <- s;
    v <- t
  ) yield opt.map(_ == v)

Upvotes: 2

Related Questions