编写接受具有特定方法的对象的方法的语法

发布于 2024-12-13 17:52:23 字数 570 浏览 0 评论 0原文

我想编写一个通用的辅助方法:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

小清晰的声音 2024-12-20 17:52:23

完整地给出它

type Closeable = {def close() }
def using[A,B](a: A with Closeable)(f: A => B) =
 try { f(a) } finally { a.close() }

(您也可以编写 A {def close()} 而不是 A with Closeable

测试:

case class X(i: Int) { def close() = println("closed") }
using(X(3)){x => println("i is " + x.i) }

输出:

我是3

已关闭

To give it in full

type Closeable = {def close() }
def using[A,B](a: A with Closeable)(f: A => B) =
 try { f(a) } finally { a.close() }

(you may also write A {def close()} rather than A with Closeable)

A test:

case class X(i: Int) { def close() = println("closed") }
using(X(3)){x => println("i is " + x.i) }

output:

i is 3

closed

抚你发端 2024-12-20 17:52:23

这称为结构类型

This is called a structural type.

追我者格杀勿论 2024-12-20 17:52:23

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文