簡體   English   中英

如何用隱式指定函數參數?

[英]How to specify function parameter with implicit?

我想傳遞一個帶有簽名的函數

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

帶簽名的函數(作為inserter

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

如何指定inserter具有隱式Session

首先,您應該了解如何從方法中創建一個需要隱式的函數

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

對於任何其他咖喱函數, 它都有效。 我希望有一天,scala會變得足夠聰明,可以支持相同的隱式方式。

PS在您的特定情況下:

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

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

您無需指定insert使用隱式。 唯一的要求是在使用它時應該有一個隱式值可用。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM