Scala - 具有隐含值的currying函数

时间:2015-08-12 20:09:13

标签: scala functional-programming

我已经解决了scala implicits的问题,我在这里发布了一个简化版本。

我有一个叫SomeClass的类,它包含一个隐含的val a = 3;

我创建了一个特性,我打算与SomeClass一起使用,如下所示:

 trait TestSum {
    def sum(a:Int)(b:Int)(implicit c: Int): Unit = {
      a + b + c
    }

    val sum_a = sum(1) _
  }

Sum_a显然不起作用,因为它需要一个隐式值c,可以在SomeClass范围内访问。将sum_a移动到SomeClass解决了这个问题,但在我的代码中有点混乱。对此有什么好的解决方案吗?

2 个答案:

答案 0 :(得分:6)

您可以要求隐含在实现者中存在,如下所示:

trait TestSum {
  implicit def c: Int

  def sum(a:Int)(b:Int): Unit = {
    a + b + c
  }

  val sum_a = sum(1) _
}

答案 1 :(得分:4)

Scala中的函数不能有隐式参数,所以当你对一个方法进行eta-expansion(_)把它变成一个函数时,它会看起来正确然后在范围内找到一个有效的隐式参数填写它。就目前而言,您的代码在范围内没有隐式Int,因此扩展失败。如果您将其移至SomeClass并且具有隐式Int,则会使用隐含所需的Int

例如:

scala> def foo(i: Int)(implicit s: String): String = i.toString ++ " " ++ s
foo: (i: Int)(implicit s: String)String

scala> foo _
<console>:10: error: could not find implicit value for parameter s: String
              foo _
              ^

scala> implicit val s: String = "number"
s: String = number

scala> foo _
res1: Int => String = <function1>

scala> res1(5)
res2: String = 5 number

可以在此处找到更多信息:http://tpolecat.github.io/2014/06/09/methods-functions.html