Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active February 3, 2026 20:26
Show Gist options
  • Select an option

  • Save dacr/77ee3125d7823a2eb7ff7aae34aa3aaf to your computer and use it in GitHub Desktop.

Select an option

Save dacr/77ee3125d7823a2eb7ff7aae34aa3aaf to your computer and use it in GitHub Desktop.
Auto close/dispose resource / published by https://github.com/dacr/code-examples-manager #671d5671-7524-476e-9b66-744ca9bbaf6f/8190c696985cb1a42faf3357750571374e3e3aed
// summary : Auto close/dispose resource
// keywords : scala, autoclose, autodispose, @testable
// publish : gist
// authors : David Crosson
// license : Apache License Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
// id : 671d5671-7524-476e-9b66-744ca9bbaf6f
// created-on : 2020-05-31T19:54:52Z
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// ---------------------
//> using scala "3.4.2"
// ---------------------
// ----------------------------------
// -- The legacy way
class That() {
def sayHello():Unit = {
println("Hello")
}
def close():Unit = {
println("Closed")
}
}
import reflect.Selectable.reflectiveSelectable
def using[R, T <: { def close():Unit }](getres: => T)(doit: T => R): R = {
val res = getres
try doit(res) finally res.close()
}
using(new That()) {that =>
that.sayHello()
}
// ----------------------------------
// -- The scala 2.13 way
import scala.util.Using
class ThatAgain() extends AutoCloseable {
def sayHello():Unit = {
println("Hello")
}
override def close():Unit = {
println("Closed")
}
}
Using(new ThatAgain()) { that =>
that.sayHello()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment