I have the following Scala code:
def f(x: Int, y: Int): Option[String] = x*y match {
case 0 => None
case n => Some(n.toString)
}
val data = List((0, 1), (1, 0), (2, 3), (4, -1))
data flatMap {case (x, y) => f(x, y)}
But, the last line is too verbose so I tried all of these and none of them compiles.
data flatMap f
data flatMap f.tupled
data flatMap Function.tupled(f)
data flatMap {f _}
data flatMap (f _).tupled
data flatMap f(_)
What am I doing wrong? The only thing that works is this:
(data map Function.tupled(f)).flatten
I thought a map
followed by flatten
can always be replaced by flatMap
, but although the above line compiles, this does not:
data flatMap Function.tupled(f)