private val alwaysTrue = (_, _) => true
Causes the compiler to complain that it needs the types for both _
's. Why? They're just discarded anyway, shouldn't they be inferred to be Scala.Any
?
private val alwaysTrue = (_, _) => true
Causes the compiler to complain that it needs the types for both _
's. Why? They're just discarded anyway, shouldn't they be inferred to be Scala.Any
?
You must explicitly provide the parameter types for anonymous functions, unless something else expects a specific type--in which case the compiler will try to infer that type, if it can. It's in the SLS 6.23 :
If the expected type of the anonymous function is of the form
scala.Functionn[S1,…,Sn, R]
, the expected type ofe
isR
and the typeTi
of any of the parametersxi
can be omitted, in whichcaseTi = Si
is assumed. If the expected type of the anonymous function is some other type, all formal parameter types must be explicitly given, and the expected type ofe
is undefined.
I'm reading between the lines just a bit, but there is no expected type, so you must explicitly provide the types.
private val alwaysTrue = (_: Any, _: Any) => true
In cases where you have something like List(1, 2, 3).filter(_ > 3)
, the expected type is Int => Boolean
, so it isn't necessary to provide the parameter type.