scala - 在 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 为玩具问题提供了一个很好的解决方案,但仅在定义期间隐式资源已经在范围内时才有效。
当隐式从范围中删除时,定义失败
解决方案
您可以将其编写为 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
调用时完成的。
推荐阅读
- node.js - 如何在 react-native 中实现用户发布/提要
- python - C++ 使用 ShellExecuteA 执行 python 文件
- c# - Windows UWP BluetoothLE 配对
- python - 如何向特定频道发送加入/离开消息
- kubernetes - 创建入口资源
- javascript - 在 Promise 的存储桶中获取所有 Amazon S3 文件
- gradle - 阿帕奇骆驼石英2没有运行
- c - 无法在 Ubuntu 中运行已编译的文件
- asp.net - ASP.NET Core 在 Internet 上不可用
- java - 无法在 Java Web 项目 Netbeans 12.4 上加载或 js