Why do I need to specify types for unimportant inputs?

private val alwaysTrue = (_, _) => true 

It makes the compiler complain that it needs types for _ . What for? In any case, they are simply discarded, should they not be considered Scala.Any ?

+4
source share
1 answer

You must explicitly specify parameter types for anonymous functions, unless something expects a specific type β€” in this case, the compiler will try to infer that type, if possible. It is located in SLS 6.23 :

If the expected type of the anonymous function is scala.Functionn[S1,…,Sn, R] , the expected type of e is R , and the type Ti any of the parameters xi can be omitted, in which caseTi = Si . If the expected type of the anonymous function is some other type, all formal parameter types must be explicitly specified , and the expected type of e is undefined.

I read the lines a bit, but there is no expected type, so you must explicitly provide 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 there is no need to specify the type of parameter.

+1
source

All Articles