Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can I get a function from an overloaded method in scala?

Tags:

scala

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

like image 799
jxstanford Avatar asked Oct 19 '11 04:10

jxstanford


1 Answers

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)

like image 118
Ben Avatar answered Sep 21 '22 18:09

Ben