首页 > 解决方案 > 在 Scala 中返回隐式函数

问题描述

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

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)这将按预期打印。到现在为止还挺好

但是,有时我想在单行中调用此方法,这迫使我将隐式显式化。

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 为玩具问题提供了一个很好的解决方案,但仅在定义期间隐式资源已经在范围内时才有效。

未找到隐式

当隐式从范围中删除时,定义失败

标签: scalaimplicit

解决方案


您可以将其编写为 curried 函数,并在第一次使用时使用 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调用时完成的。


推荐阅读