Answering since the existing answers don't really explain when _
is needed, just "sometimes" or "in some cases".
A very important concept to understand in Scala is expected type. In your first example the expected type for argument of map
is Double => B
with some unknown B
; in the second it's Double => Double
. When the expected type is a function type and a method name is passed, it'll be automatically converted to a function. So, as comments say, the second example works without _
. It's only necessary where there is no expected type, say
val f = sqrt _
There can also be issues when the method is overloaded, but there just adding _
generally won't work either; instead, you'll specify the argument type to show which method is used, e.g. max(_: Int, _: Int)
or max(_: Double, _: Double)
.
Thanks seems _ has different meaning in different context in scala
Yes, quite a few: What are all the uses of an underscore in Scala?