如何将从方法返回的元组应用于Scala中的多态方法

时间:2014-08-14 19:43:18

标签: scala

我有两个set方法定义如下:

  def set(value: Any) : Unit = {
    val (a, b, c, d) = value.asInstanceOf[(Int, Int, Int, Int)]
    set(a, b, c, d)
  }
  def set(aValue: Int, bValue: Int, cValue: Int, dValue: Int) = {
    ...
  }

我还有一个生成元组的方法:

def getResults() = (1,2,3,4)

我想将getResults()作为set方法的输入。

((set _).tupled)(getResults())

问题是这个代码没有编译,因为set定义了两次。我该如何解决这个问题?

enter image description here

1 个答案:

答案 0 :(得分:3)

IDE的演示编译器似乎比应该更加困惑。 如果您在REPL中尝试代码,它将起作用。不幸的是,set的分辨率取决于定义顺序。

这是一个scala REPL会话,展示了这个事实:

scala> :paste
// Entering paste mode (ctrl-D to finish)

def set(value: Any) : Unit = {
    val (a, b, c, d) = value.asInstanceOf[(Int, Int, Int, Int)]
    set(a, b, c, d)
  }

 def set(aValue: Int, bValue: Int, cValue: Int, dValue: Int) = println("ok")

// Exiting paste mode, now interpreting.

set: (value: Any)Unit <and> (aValue: Int, bValue: Int, cValue: Int, dValue: Int)Unit
set: (value: Any)Unit <and> (aValue: Int, bValue: Int, cValue: Int, dValue: Int)Unit

scala> (set _).tupled((1, 2, 3, 4))
ok

scala> :paste
// Entering paste mode (ctrl-D to finish)

 def set(value: Any) : Unit = {
    val (a, b, c, d) = value.asInstanceOf[(Int, Int, Int, Int)]
    set(a, b, c, d)
  }

// Exiting paste mode, now interpreting.

set: (value: Any)Unit

scala> (set _).tupled((1, 2, 3, 4))
<console>:9: error: value tupled is not a member of Any => Unit
              (set _).tupled((1, 2, 3, 4))

一般来说,混淆来自于与部分应用函数混合的重载。

重载方法使用它们的参数列表消除歧义,但是,当您部分应用它们时,您将丢弃此信息,并且您只能希望编译器将看到&#34; right&#34;错误之前的set

但是,我怀疑这是在任何地方指定的,所以你基本上将程序的语义绑定到编译器实现细节:坏主意,不是吗?

正如特拉维斯·布朗在评论中已经建议的那样,为什么不仅仅avoid overloading让你的生活(和编译器)更快乐?