如何使用多个隐式参数创建scala匿名函数

时间:2013-07-18 02:31:26

标签: scala

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

  1. 这甚至可能吗?
  2. 如果有可能,语法是什么?
  3. 
    
    
           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()
              }
            }
    
    

1 个答案:

答案 0 :(得分:16)

你正在讨论run2内的函数,所以run2仍然需要一个非curried函数。请参阅以下代码,了解适用的版本:

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()
  }
}