Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala "a" + _.toString not behaving like "a".+(_.toString)

Tags:

scala

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

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

Is the same as:

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

I came across an occasion where this is not happening, when there is a placeholder. I was doing something more complex, but it can be distilled to:

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's the difference here? What am I missing?

Jordi

like image 243
agile_jordi Avatar asked Nov 30 '22 14:11

agile_jordi


1 Answers

The _ placeholder can only appear at the topmost Expr in its function. That means

(_.toString)

is itself a function, and "a" + some function of unknown type doesn't make much sense to the compiler.

like image 187
jpalecek Avatar answered Dec 02 '22 02:12

jpalecek