I am learning Scala and have a very basic question. Consider the following two expressions using the placeholder syntax -
// Syntax A
val fnA = (_: Int, _: Int) => _ / _
// Syntax B
val fnB = (_: Int) / (_: Int)
and their attempted applications -
// Syntax A
fnA(33, 3)
// Syntax B
fnB(33, 3)
Out of these two, only B and App(B) are valid syntax and I am not sure why. If the compiler is able to infer the arguments (and the order to apply them in) in fnB
why is it not able to do it for fnA
? I am basing my question on the premise that fnB
is a shorthand for fnA
and I am pretty certain there's a flaw in that reasoning. I am just not sure what the flaw is.
The meaning of underscores on the left of arrow
=>
are different from the meaning of underscores around the infix operator
/
The former mean something like
whilst the latter is a shorthand for defining a function of two arguments
For example,
desugars to something like
where we see arguments
a
andb
are not used in the body which happens to be yet another function((x: Int, y: Int) => x / y)
.Daniel documents the two meanings as
As a side-note, consider a somewhat analogous situation at the typelevel involving type constructors and their bounds where the meaning of underscore depends on the context
Personally, my mind tricks me to think it is equivalent to
however that is not the case, and the meaning of the underscore on the left of
<:
is different from the meaning on the rightNote how
x
does not appear inIterable[y] forSome {type y}
. Adrian documents this under Common Pitfalls:and in a comment to type bounds on type constructor
Hence we should be careful to interpret the meaning of the underscore within its context.