Skip to content

Instantly share code, notes, and snippets.

@aktau
Created January 4, 2012 22:04
Show Gist options
  • Save aktau/1562427 to your computer and use it in GitHub Desktop.
Save aktau/1562427 to your computer and use it in GitHub Desktop.
Scala test of using + Future
//output:
/*
Here we go
closed: meee
closed: bloo
closed: bla
I feel used
I feel used
-----------
I feel used
closed: meee
closed: bloo
closed: bla
*/
import akka.dispatch.Future
object Test {
def using[A, B <: {def close(): Unit}] (closeable: B) (f: B => A): A = {
try { f(closeable) }
finally { closeable.close() }
}
def main(args: Array[String]): Unit = {
println("Here we go")
val der = Future {
using (Cl("bla")) { connection =>
using (Cl("bloo")) { statement =>
using (Cl("meee"))(identity)
}
}
} onComplete { fut => fut.get.use() } onResult { case cl => cl.use() }
println("---------")
// the alternate yet ugly way that does perform as expected
val dem = Future {
(Cl("bla"), Cl("bloo"), Cl("meee")) // val (conn, stat, rs) =
} onResult {
case (cl1, cl2, cl3) =>
cl3.use()
cl3.close()
cl2.close()
cl1.close()
/*
* alternatively
* using (cl1) { cl3a => using (cl2) { cl2a => using (cl1) { cl1a => cl1a.use() } } }
*/
}
}
}
case class Cl(a: String) {
def close(): Unit = {
//do nothing
println("closed: " + a)
}
def use() = {
println("I feel used")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment