Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

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)
like image 911
devth Avatar asked Mar 11 '26 02:03

devth


1 Answers

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.)

like image 93
Rex Kerr Avatar answered Mar 13 '26 07:03

Rex Kerr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!