编写接受具有特定方法的对象的方法的语法
我想编写一个通用的辅助方法:
def using(closeable: [B has close() method], callback: [B has close() method] => A): A {
try {
callback(closeable)
} finally {
closeable.close()
}
}
目的是我可以将它与任何具有 close() 方法的东西一起使用:
using(new FileInputStream(...)) {
stream => stream.read()
}
using(dataSource.getConnection) {
conn => using(conn.createStatement()) {
statement => using(statement.executeQuery("...")) {
rs => rs.getString(1)
}
}
}
我正在寻找的是它的命名方式,这样我就可以自己搜索语法,以及语法本身。
I want to write a generic helper method:
def using(closeable: [B has close() method], callback: [B has close() method] => A): A {
try {
callback(closeable)
} finally {
closeable.close()
}
}
with the intent being that I can use this with anything that has a close() method:
using(new FileInputStream(...)) {
stream => stream.read()
}
using(dataSource.getConnection) {
conn => using(conn.createStatement()) {
statement => using(statement.executeQuery("...")) {
rs => rs.getString(1)
}
}
}
What I'm looking for is how this is named, such that I could have searched for the syntax myself, and the syntax itself.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
完整地给出它
(您也可以编写
A {def close()}
而不是A with Closeable
)测试:
输出:
To give it in full
(you may also write
A {def close()}
rather thanA with Closeable
)A test:
output:
这称为结构类型。
This is called a structural type.
Debilski 是对的,其语法是
close: { def close() }
编辑:这里有一个替代链接 .NET 的 Scala 实现,类似于您想要基于对象及其 apply 方法使用的 using 构造。
Debilski is right, the syntax for that would be
closable: { def close() }
Edit: Here's a link to an alternative Scala implementation of the .NET like using construct you want to use based on an object and it's apply method.