1

What is the reason the second function does nor compile:

case class Person(name: String)
def f1(op: Option[Person]) = op.map(p => Seq(p.name)) // GOOD
def f2(op: Option[Person]) = op.map(Seq(_.name))      // WRONG

P.S. I see comments pointing stackoverflow.com/a/7673633/6059889 as an answer to the question, but I do not understand how this answers it. According to rule 2, I'd expect Seq(_.name) to become x => Seq(x.name), which should work.

P.P.S. Thanks, Dima, for the link to: Underscore in Named Arguments: link to _ always picks the tightest non-degenerate scope it can, I get it.

Assen Kolov
  • 4,143
  • 2
  • 22
  • 32
  • 1
    https://stackoverflow.com/a/7673633/6059889 this answer contains the different interpretations of the _ syntax in lambda functions. I think in the second case it will interpret the Seq as an anonymous function and can't infer its return type. – Steffen Schmitz May 26 '17 at 10:02
  • Yes, these should be merged – Phasmid May 26 '17 at 12:08
  • Please, explain how the links answers this question. In the second case you mention `Seq(_.name))` becomes `x => Seq(x.name)`, which is exactly what is needed. How does that explain why it is wrong? – Assen Kolov May 26 '17 at 12:55
  • 2
    @AssenKolov It actually becomes `Seq(x => x.name)`. A better explanation is here: https://stackoverflow.com/questions/5259006/underscore-in-named-arguments – Dima May 26 '17 at 13:16

0 Answers0