3
votes

I was playing around on the simplyscala.com REPL and tried to get references to methods of objects. It is working with Strings but not with Integeres as I expected and I am a little confused, so help would be appreciated.

This...

"abc".+ _
res0: (Any) => java.lang.String = 

...works as expected. I would like it better if it would show the function body after the = sign (maybe in a shortened form) but it gives me the method reference instead of calling the (empty) method as I expect.

However this...

42.+ _

error: missing parameter type for expanded function ((x$1) => 42.0.+(x$1))
   42.+ _
        ^

...gives me a strange error. How exactly does _ work here? I also tried it more explicit by using parentheses to create an Integer and not having it interpreted as a floating:

(42).+ _

error: ambiguous reference to overloaded definition,
both method + in class Int of type (x$1: Char)Int
and  method + in class Int of type (x$1: Short)Int
match expected type ?
       (42).+ _
            ^

It gives me another unexpected error though, but I understand that the compiler does not know which of the overloaded methods I want have a reference to.

So my question is: what does the error in my 2. code example tell me? And how do I make the compiler choose one of the methods in my 3. code example?

Thanks!

1

1 Answers

3
votes

On a quick look it's the same issue, simply resolved differently by the compiler: it doesn't know which overload you're talking about. By the way, in scala 2.11 they both throw the same error, since you can't end a floating point literal with a . anymore)

If you need to pick one, you will have to be explicit:

(42: Int) + (_: Int)

or

val x: Int => Int = 42.+ _

They will both work.