devth
devth

Reputation: 2750

Why does scala sometimes need args named in an anonymous function?

I don't understand why scala needs me to sometimes name args to anon fns:

scala> case class Person(name: String)
defined class Person

scala> def reverseString(s: String) = s.reverse
reverseString: (s: String)String

scala> val p = Some(Person("foo"))
p: Some[Person] = Some(Person(foo))

scala> p map { reverseString(_.name) }
<console>:12: error: missing parameter type for expanded function ((x$1) => x$1.name)
              p map { reverseString(_.name) }

// why does it only work when I name the argument? I'm not even telling it the type.
scala> p map { p => reverseString(p.name) }
res9: Option[String] = Some(oof)

// and shouldn't this fail too?
scala> p map { _.name.reverse }
res13: Option[String] = Some(oof)

Upvotes: 3

Views: 572

Answers (2)

Rex Kerr
Rex Kerr

Reputation: 167871

The answer is in the error message, but cryptically so:

(x$1) => x$1.name

Wait, what? You wanted x$1 => reverseString(x$1.name).

So now you see exactly what went wrong: it assumed the function was inside the reverseString parens (i.e. you wanted to pass a function to reverseString). By explicitly naming the variable, you demonstrate to it that it was mistaken.

(It gives that message because once it assumes that reverseString should be passed a function, it doesn't know what type to make that function since reverseString actually wants a string, not a function.)

Upvotes: 4

Jordan Denison
Jordan Denison

Reputation: 2727

I believe this is what is referred to as Type Inference. Also, _ is just a placeholder. (You already defined p as type Some[Person] so the compiler is smart enough to figure that out when used the way you did)

Upvotes: 0

Related Questions