2013-07-18 45 views
8

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

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

+1

的[功能与多个隐参数文字(可能重复http://stackoverflow.com/questions/14072061/function-literal-with-multiple-implicit-参数) – Noah

+0

它不工作在我的情况在“run2”,我使用scala 2.10.0。 – Michael

+0

你的类型没有咖喱,你在'run2'函数本身中进行曲调。 'fType = Object => String => Long => Object'会起作用。 – Noah

回答

15

你讨好里面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() 
    } 
} 
+0

我的错误。感谢了。 – Michael

相关问题