Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active April 2, 2023 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/77ee3125d7823a2eb7ff7aae34aa3aaf to your computer and use it in GitHub Desktop.
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/85fcf63b2b7579be403137570a5184199ab5c314
// summary : Auto close/dispose resource
// keywords : scala, autoclose, autodispose, @testable
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// 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.1.1"
// ---------------------
// ----------------------------------
// -- 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