在 Scala 中返回隐式函数

时间:2021-01-15 14:10:06

标签: scala implicit

我目前有这样的设置,我有一个方法和一些隐式资源,该方法返回一个我可以稍后在我的代码中使用的函数。

type AResource = Int

def testA(s: String)(implicit aResource: AResource): (Double) => (String, Int) = (d: Double) => {
  (s + d, d.toInt * aResource)
}

implicit val ar:AResource = 3

val fA = testA("org: ")
fA(3.1415)

这将按预期打印 (org: 3.1415,9)。到目前为止一切顺利

但是有时我想在 oneliner 中调用这个方法,这迫使我使隐式显式。

val fA2 = testA("org2: ")(ar)(1.123)

这似乎是一个小小的不便,但问题实际上更复杂一些,因为我的方法使用了 TypeTag 并在函数中注入了隐式 typeTag。

我正在寻找的是一种定义 testA 的方法,以便返回函数实现隐式。

像这样(显然行不通)

def testB(s: String): (Double, AResource) => (String, Int) = (d: Double)(implicit aResource: AResource) => {
 (s + d, d.toInt * aResource)
}

然后我就可以跑了

testB("org2: ")(1.123)

担心最低层的隐含

更新:

我至少找到了这个解决方案,但它还不是 100% 完美

def testC(s: String): (Double) => (AResource) => (String, Int) = (d: Double) => { implicit aResource: AResource => {
  (s + d, d.toInt * aResource)
}}

val c:(String, Int) = testC("org: ")(2.4)(ar)

它确实将隐式向下移动,但我仍然必须通过硬编码。

更新 2:

Tim 为玩具问题提供了一个很好的解决方案,但只是因为隐式资源在定义期间已经在范围内。

No implicits found

当隐式从作用域中移除时,定义失败

1 个答案:

答案 0 :(得分:3)

你可以把它写成柯里化函数,第一次使用时使用 Eta 扩展:

def testC(s: String)(d: Double)(implicit aResource: AResource) =
  (s + d, d.toInt * aResource)

val fC = testC("org: ") _
fC(3.1415)

testC("33")(2.0)

以前的错误答案

您可以像这样实现 testB

def testB(s: String) = {
  def f(d: Double)(implicit aResource: AResource) = (s + d, d.toInt * aResource)

  f _
}

这两种方式都可以调用:

val fB = testB("org: ")
fB(3.1415)

testB("org2: ")(1.123)

这会失败,因为隐式解析是在 testB 内完成的,而不是在调用 f 时完成。