Scala "a" + _.toString does not behave like "a". + (_. toString)

As far as I know, using the infix operator in Scala should be equivalent to calling a method. So:

scala> "a" + 3.toString res0: java.lang.String = a3 

Same as:

 scala> "a".+(3.toString) res1: java.lang.String = a3 

I came across a case where this does not happen, when there is a placeholder. I did something more complex, but it could be overtaken:

 scala> def x(f:(Int)=>String) = f(3) x: (f: Int => String)String scala> x("a" + _.toString) res3: String = a3 

So far so good. But...

 scala> x("a".+(_.toString)) <console>:9: error: missing parameter type for expanded function ((x$1) => x$1.toString) x("a".+(_.toString)) 

What is the difference here? What am I missing?

Jordi

+4
source share
2 answers

Placeholder _ can only be displayed in the upper Expr in its function. It means

 (_.toString) 

itself is a function, and "a" + some function of unknown type does not make much sense to the compiler.

+11
source

Your assessment of infix notation is correct, but your understanding of placeholder parameters is erroneous.

When using underscore as a placeholder parameter, you create a function. The question is what are the boundaries of this function: where does it start, where does it end? For example, consider this expression:

 _ + _ + _ 

How to translate it? Here are a few alternatives:

 (x, y, z) => { x + y + z } (x, y) => { (z) => { x + y } + z } (x) => { x + { (y, z) => y + z } } 

Well, the Scala rule is that the scope is the innermost expression, delimited by parentheses, or the whole expression otherwise. So, in practice, you wrote two different things:

 x("a" + _.toString) // is the same thing as x((y) => "a" + y.toString) x("a".+(_.toString)) // is the same thing as x("a".+((y) => y.toString)) 
+10
source

All Articles