10

我有名为“run1”和“run2”的 scala 函数,它们接受 3 个参数。当我应用它们时,我想提供一个带有隐式参数的匿名函数。在下面的示例代码中,它在这两种情况下都不起作用。我想知道是否

  1. 这甚至可能吗?
  2. 如果可能,语法是什么?



       object Main extends App {
          type fType = (Object, String, Long) => Object

          def run1( f: fType ) {
            f( new Object, "Second Param", 3)
          }

          run1 { implicit (p1, p2, p3) => // fails
            println(p1)
            println(p2)
            println(p3)
            new Object()
          }

          def run2( f: fType ) {
            val fC = f.curried
            fC(new Object)("Second Param")(3)
          }

          run2 { implicit p1 => implicit p2 => implicit p3 => // fails
            println(p1)
            println(p2)
            println(p3)
            new Object()
          }
        }

4

1 回答 1

17

您正在对内部函数进行柯里化,run2因此run2仍然需要一个非柯里化函数。请参阅下面的代码以获取有效的版本:

object Main extends App {
  type fType = (Object, String, Long) => Object
  type fType2 = Object => String => Long => Object //curried

  def run1( f: fType ) {
    f( new Object, "Second Param", 3)
  }

  // Won't work, language spec doesn't allow it
  run1 { implicit (p1, p2, p3) => 
    println(p1)
    println(p2)
    println(p3)
    new Object()
  }

  def run2( f: fType2 ) {
    f(new Object)("Second Param")(3)
  }

  run2 { implicit p1 => implicit p2 => implicit p3 =>
    println(p1)
    println(p2)
    println(p3)
    new Object()
  }
}
于 2013-07-18T02:36:28.863 回答