Nie*_*and 5 functional-programming scala
我已经解决了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) _
}
Run Code Online (Sandbox Code Playgroud)
Sum_a显然不起作用,因为它需要一个隐式值c,可以在SomeClass范围内访问.将sum_a移动到SomeClass解决了这个问题,但在我的代码中有点混乱.这有什么好的解决方案吗?
您可以要求隐含在实现者中存在,如下所示:
trait TestSum {
implicit def c: Int
def sum(a:Int)(b:Int): Unit = {
a + b + c
}
val sum_a = sum(1) _
}
Run Code Online (Sandbox Code Playgroud)
Scala 中的函数不能有隐式参数,所以当你_对一个方法进行eta-expansion (the ) 以将它变成一个函数时,它会在当时和那里寻找有效的隐式参数来填充它。 ,您的代码没有隐式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
Run Code Online (Sandbox Code Playgroud)
更多信息可以在这里找到:http : //tpolecat.github.io/2014/06/09/methods-functions.html