在 Scala 中是否可以用相反的方式进行柯里化?
让我们假设这个函数:
def autoClosing(f: {def close();})(t: =>Unit) = {
t
f.close()
}
和这个片段:
val a = autoClosing(new X)(_)
a {
println("before close")
}
是否可以柯里化第一部分?像这样:
val a = autoClosing(_) { println("before close") }
这样我就可以发送应该执行关闭的对象,并在它们上执行相同的块?
Let's assume this function:
def autoClosing(f: {def close();})(t: =>Unit) = {
t
f.close()
}
and this snippet:
val a = autoClosing(new X)(_)
a {
println("before close")
}
is it possible to curry the first part? Something like:
val a = autoClosing(_) { println("before close") }
so that I could send the objects on which close should be performed, and have the same block executed on them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,只要您给出占位符字符的类型,您给出的代码片段就可以工作。
因此,您正在寻找的代码是:
它可以按预期编译和工作:)。
一些注意事项:
close
方法的AnyRef
类型定义类型别名,例如type Closeable = AnyRef { def close()}
,或适当的接口。autoClosing(_: Closeable){ ... }
实际上相当于以下扩展的匿名函数:c: Closeable =>自动关闭(c){...}
。通配符只是部分应用函数的简写。您需要提供_
的类型,因为类型推断器在这种情况下无法推断类型。希望有帮助,
-- Flaviu Cipcigan
Yes, the snippet you have given works, as long as you give the type of the placeholder character.
Therefore, the code you are looking for is:
which compiles and works as expected :).
A couple of notes:
AnyRef
type having aclose
method, something liketype Closeable = AnyRef {def close()}
, or an appropriate interface.autoClosing(_: Closeable){ ... }
is actually equivalent to the following expanded anonymous function:c: Closeable => autoClosing(c){ ... }
. The wildcard character is just shorthand for a partially applied function. You need to give the type of the_
as the type inferer unfortunately cannot infer the type in this case.Hope it helps,
-- Flaviu Cipcigan
或者,您可以翻转参数:
在您的情况下:
编辑:
我添加了一些大括号来帮助人类解析器:
Flip 将函数
(A1 => (A2 => B))
转换为(A2 => (A1 => B))
。Alternatively you can flip the parameters:
In your case:
Edit:
I've added some braces to help the human parser:
Flip converts a function
(A1 => (A2 => B))
to(A2 => (A1 => B))
.我很高兴看到现在有这么多人回答 Scala 问题。然而,这确实让我更难想出一些东西。这是 Flaviu 的 解决方案中采用另一种方法。
当然,正确的解决方案是以与您将如何使用它兼容的方式定义 autoClosing。
I'm happy to see so many people answering Scala questions nowadays. It does make it harder for me to come up with something, however. Here's an alternative to Flaviu's solution.
Of course, the proper solution is to define autoClosing in a way compatible with how you are going to use it.