Let's say that I have two methods defined with the same name and return, but different params:
def overload(x: Int) = x.toString
def overload(s: String) = s
Now I want to convert one of them to a function. If the method weren't overloaded, I would do this:
val f = overload _
But since it is, the compiler rightly complains about an ambiguous reference. Is there any way to make a function of one or the other of the overload methods other than to rename one of them?
Thanks!
John
The way the compiler knows which overload
to call when you call it directly is by knowing the type of the argument it's applied to. overload someInt
can only be referring to overload(x: Int)
, so there's no ambiguity.
When you make a function from it, you haven't supplied an argument (yet), so the compiler has no idea what type you want your function to be, so it doesn't know which overload
you're referring to.
The easy way to fix that is to explicitly tell it the type:
val f : Int => String = overload _
or:
val f = (x : Int => overload x)
or:
val f = overload (_ : Int)
(note: I haven't tested these yet, but some variation on them should work)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With