Created
May 31, 2012 16:15
-
-
Save tinoadams/2844493 to your computer and use it in GitHub Desktop.
Using the using package
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
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