Last active
May 25, 2024 10:19
-
-
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/2b3a1e6e54eabde44ce2ce1883bc72ed737fa496
This file contains hidden or 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.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