scala - 我可以重载柯里化方法吗? [英] scala - Can I overload curried methods?

查看:50
本文介绍了scala - 我可以重载柯里化方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 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.

推荐答案

您不能为此使用重载,因为由于柯里化,将有两个 foo 方法仅在返回类型上有所不同.

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

您可以使用 Scala 2.8 的可选和命名参数来近似这一点,但您必须将该方法调用为 foo(1)(1)().例如,

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

这篇关于scala - 我可以重载柯里化方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆