Last active
April 2, 2023 10:11
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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