Skip to content

Instantly share code, notes, and snippets.

@dwhitney
Created July 5, 2011 22:42
Show Gist options
  • Select an option

  • Save dwhitney/1066130 to your computer and use it in GitHub Desktop.

Select an option

Save dwhitney/1066130 to your computer and use it in GitHub Desktop.
import scala.concurrent.stm._
case class Account(accountNo: String, balance: Int){
def credit(amount: Int) = this.copy(balance = (balance + amount))
def debit(amount: Int) = this.copy(balance = (balance - amount))
}
object Bank{
val accountsRef = Ref(Map("from" -> Account("from", 500), "to" -> Account("to", 500) ))
def transfer(fromNo: String, toNo: String, amount: Int): Unit = {
atomic{ implicit t =>
var accounts = accountsRef()
val (from, to) = (accounts(fromNo), accounts(toNo))
if(from.balance > amount){
accounts = accounts + (to.accountNo -> to.credit(amount))
accounts = accounts + (from.accountNo -> from.debit(amount))
accountsRef() = accounts
}
}
}
def main(args: Array[String]): Unit = {
Bank.transfer("to", "from", 50)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment