Skip to content

Instantly share code, notes, and snippets.

@tinoadams
Created May 31, 2012 16:15
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 tinoadams/2844493 to your computer and use it in GitHub Desktop.
Save tinoadams/2844493 to your computer and use it in GitHub Desktop.
Using the using package
import java.io.BufferedReader
import java.io.ByteArrayInputStream
import java.io.InputStreamReader
import utils.using._
object Main extends App {
// the "used" instance is passed to the body i.e. "in" is of type BufferedReader
using(new BufferedReader(new InputStreamReader(new ByteArrayInputStream("Testing using".getBytes)))) { in =>
println(in.readLine)
}
val i1 = new BufferedReader(new InputStreamReader(new ByteArrayInputStream("Testing".getBytes)))
val i2 = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(" using".getBytes)))
// here the instances are not passed to the body
// couldn't think of a way preserving the type of each instance
using(i1, i2) {
print(i1.readLine)
println(i2.readLine)
}
// will throw java.io.IOException: Stream closed
i1.readLine
// slightly more useful
val emf = Persistence.createEntityManagerFactory("persistence_unit")
using(emf.createEntityManager) { em =>
// use em here...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment