2

我对以下代码有编译问题。

object Main {
    def main(args:Array[String]) = {
      def collectBigger(median:Int)(values:Int*) = values.filter { _ > median }
      val passedRanks = collectBigger(5)_
      //this compiles
      println(passedRanks(Seq(5,9,5,2,1,3)))
      //this doesn't
      println(passedRanks(5,9,5,2,1,3))
    }
}

该示例的灵感来自 com.agical.gsl,它是 swt 的 scala 适配器。我假设它在 scala 2.8 之前使用了 scala 功能。

该错误too many arguments for method apply: (v1: Seq[Int])Seq[Int] in trait Function1与变量参数如何传递给部分应用的函数有关。

感谢您提供的任何提示。

4

3 回答 3

10

简单来说,你可以在 scala 中使用 varargs方法,但不能使用 varags function。为什么?好吧,所有函数都有一个FunctionN[T1..TN,R]类型。在你的情况下,它是Function1[Seq[Int], Seq[Int]].

“varargs 函数”根本没有类型,因此每当您将方法转换为函数时,都必须将其脱糖到Seq..符号中。

于 2016-05-30T13:43:30.050 回答
0

你曾经能够:

$ scala210 -Yeta-expand-keeps-star
Welcome to Scala version 2.10.5 (OpenJDK 64-Bit Server VM, Java 1.7.0_95).
Type in expressions to have them evaluated.
Type :help for more information.

scala> def f(vs: Int*) = vs.sum
f: (vs: Int*)Int

scala> f(1,2,3)
res0: Int = 6

scala> val g = f _
g: Int* => Int = <function1>

scala> g(1,2,3)
res1: Int = 6

但不再。

https://issues.scala-lang.org/browse/SI-6816

于 2016-05-30T19:48:31.210 回答
0

根据 Rob Norris 的建议,使用 apply 的解决方法

object Main {
  def main(args: Array[String]) = {
    {
      //workaround use Seq as requested
      def collectBigger(median: Int)(values: Int*) = values.filter { _ > median }
      val passedRanks = collectBigger(5)_
      println(passedRanks(Seq(5, 9, 5, 2, 1, 3)))
      println(passedRanks(5, 9, 5, 2, 1, 3))//compile error: too many arguments for method apply: (v1: Seq[Int])Seq[Int] in trait Function1
    }

    {
      //
      def collectBigger(median: Int) = new { def apply(values: Int*) = values.filter { _ > median } }
      val passedRanks = collectBigger(5)
      import scala.language.reflectiveCalls
      println(passedRanks(Seq(5, 9, 5, 2, 1, 3)))//compile error (as expected): type mismatch; found : Seq[Int] required: Int

      //this now works
      println(passedRanks(5, 9, 5, 2, 1, 3))
    }
  }
}
于 2016-05-30T20:52:59.753 回答