Skip to content

Instantly share code, notes, and snippets.

@ahoy-jon
Created July 6, 2011 21:07
Show Gist options
  • Save ahoy-jon/1068327 to your computer and use it in GitHub Desktop.
Save ahoy-jon/1068327 to your computer and use it in GitHub Desktop.
ça gère bien les ressources Scala
object Control {
def using[Closeable <: {def close(): Unit}, B](closeable: Closeable)(useCloseable: Closeable => B): B =
try {
useCloseable(closeable)
} finally {
closeable.close()
}
}
class TestSql {
import java.sql._
import Control._
def query[B](connection: Connection, sql: String)(process: ResultSet => B): B =
using (connection) { connection =>
using (connection.createStatement) { statement =>
using (statement.executeQuery(sql)) { results =>
process(results)
}
}
}
}
class TestReader {
import java.io._;
import Control._
def run() : Unit =
using(new FileReader("FileReaderDemo.java")) {
reader => val br = new BufferedReader(reader);
var s:String = null ;
// the following is boring... you don't read files this way in scala.
}
}
@ahoy-jon
Copy link
Author

ahoy-jon commented Jul 6, 2011

  • ligne 7, ben non, on catch l'exception plus haut, si cela arrive plus bas, finally marche quand même (ou je n'ai pas compris).
  • ligne 17. Si ta connexion vient d'un pool de connexions (++ pour les pools de connexions), alors close va faire un retour au pool. Sinon, la fonction que tu passes en entrée de using fait tout ce que tu as à faire avec cette connexion (quitte à retourner Unit/void).

Pour les effets de bord ... on est déjà sur du pur IO là ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment