5

I was wondering if there exists a function (in scala or cats) which omits the result within flatMap. E.g.

Some("ignore this").ignoreArgumentFlatMap(Some("result"))

which would be the same as

Some("ignore this").flatMap(_ => Some("result"))
Nicolas Heimann
  • 2,561
  • 16
  • 27

1 Answers1

7

It is called >> in cats.

scala> import cats.implicits._
import cats.implicits._

scala> Option("ignore this") >> Some("result")
res14: Option[String] = Some(result)

The documentation explicitly says

Alias for fa.flatMap(_ => fb).

Unlike *>, fb is defined as a by-name parameter, allowing this method to be used in cases where computing fb is not stack safe unless suspended in a flatMap.

There's also productR or *>.

scala> Option("ignore this").productR(Some("result"))
res15: Option[String] = Some(result)

scala> Option("ignore this") *> Some("result")
res16: Option[String] = Some(result)

Like the doc said its argument is not by-name though. So it's more or less equivalent to

val x0 = Some("result")
Some("ignore this").flatMap(_ => x0)

There's productREval if you want an alternative evaluation strategy.

Jasper-M
  • 14,966
  • 2
  • 26
  • 37