Welcome to OGeek Q&A 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...