如何用隐式指定函数参数?

时间:2015-04-17 08:19:09

标签: scala

我想传递一个带签名的函数

def insert(o: Role)(implicit s: Session): UUID

带有签名

的函数(如inserter
def insertRows[T](instanceList: List[T], inserter: T => UUID): Unit

如何指定inserter具有隐式Session

2 个答案:

答案 0 :(得分:1)

首先,您应该了解如何从方法中创建function,这需要隐式:

scala> def a(a: Int)(implicit b: Int) = a
a: (a: Int)(implicit b: Int)Int

scala> a _
<console>:9: error: could not find implicit value for parameter b: Int
          a _
          ^ 
//I assume you can't specify implicit before `a _`, otherwise you have your answer anyway :)

scala> a(_: Int)(_: Int)
res18: (Int, Int) => Int = <function2>

然后,很清楚要通过什么:

scala> def f(f: (Int, Int) => Int) =0
f: (f: (Int, Int) => Int)Int

scala> f(a(_: Int)(_: Int))
res16: Int = 0

甚至:

scala> f(a(_)(_))
res25: Int = 0

对于任何其他curry函数this有效。我希望有一天scala会变得足够聪明,以支持同样的方式。

P.S。在您的具体情况下:

 def insertRows[T](instanceList: List[T], inserter: (T, Session) => UUID): Unit

 insertRows[Role](list, insert(_)(_))

答案 1 :(得分:0)

您不需要指定insert使用隐式。唯一的要求是在使用它时应该有一个隐含值。

implicit val s = new Session(...) // or import if defined elsewhere.
insertRows(list, insert)