Referencing overloaded methods in scala
I was playing around at the justscala.com REPL and was trying to get method references of objects. It works on strings, but not Integeres as I expected and I'm a little confused so help would be appreciated.
It...
"abc".+ _
res0: (Any) => java.lang.String =
... works as expected. I would like it to be better if it displays the function body after the sign =
(possibly in a shorthand form), but it gives me a 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 does _
it work here? I also tried to make it more explicit by using parentheses to create Integer
and not interpreting it as 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).+ _
^
This gives me another unexpected error, although I understand that the compiler doesn't know which of the overloaded methods I want to be referenced.
So my question is, what does the error in my example code tell me? And how do I force the compiler to select one of the methods in my example code?
Thank!
source to share
Take a quick look at the same problem that the compiler just solved differently: it doesn't know which overloading you're talking about. By the way, in scala 2.11 they both throw the same error as you can no longer end up floating point literal with .
)
If you need to choose one, you must be explicit:
(42: Int) + (_: Int)
or
val x: Int => Int = 42.+ _
Both of them will work.
source to share