Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala - Can I overload curried methods?

Tags:

scala

Is there a way to overload methods in Scala that take multiple parameter lists? E.g. I'd like to do this:

def foo(a: Int)(b: Int)(c: Int): Int

def foo(a: Int)(b: Int): Int

I can define it like this, but trying to call the second method like this:

foo(1)(1)

makes the compiler complain about "ambiguous reference to overloaded definition", which seems justified. Is there a way to achieve something like this? The last parameter might be considered optional in some cases, for example.

like image 504
Carl-Eric Menzel Avatar asked Feb 13 '12 22:02

Carl-Eric Menzel


1 Answers

You can't use overloading for this, since due to the currying there would be two foo methods differing only in their return type.

You can use Scala 2.8's optional and named parameters to approximate this, but you'd have to call the method as foo(1)(1)(). E.g.,

object Hello {
  def foo(a : String = "Hello,") : String = a

  def main(args: Array[String]) {
    println(foo() + foo(" world!"))
  }
}
like image 52
Fred Foo Avatar answered Oct 15 '22 16:10

Fred Foo