Skip to content

Instantly share code, notes, and snippets.

@ueshin
Created October 26, 2012 08:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ueshin/3957703 to your computer and use it in GitHub Desktop.
Save ueshin/3957703 to your computer and use it in GitHub Desktop.
Loan type class
implicit def ClosableLoan[C <: { def close(): Unit }] = new Loan[C] {
override def using[A](closable: C)(block: C => A) = try {
block(closable)
} finally { closable.close }
}
using(new FileInputStream(file)) { in =>
// do something
}
using(Tx(conn)) { c =>
// do transaction
}
trait Loan[L] {
def using[A](l: L)(block: L => A): A
}
def using[L: Loan, A](l: L)(block: L => A) = implicitly[Loan[L]].using(l)(block)
import scalaz._, Scalaz._ // needs Scalaz 7
import java.sql.Connection
sealed trait Tx
def Tx[A](conn: Connection) = Tag[Connection, Tx](conn)
implicit object TransactionLoan extends Loan[Connection @@ Tx] {
override def using[A](conn: Connection @@ Tx)(block: Connection @@ Tx => A) = try {
val r = block(conn)
conn.commit
r
} catch {
case t: Throwable =>
conn.rollback
throw t
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment