Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

scala - Can I overload curried methods?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!"))
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...