Created
July 5, 2011 22:42
-
-
Save dwhitney/1066130 to your computer and use it in GitHub Desktop.
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 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