August 2010
Intermediate to advanced
376 pages
10h 6m
English
import java.util.Date
// Account is just a base class for the domain
// objects, that are different kinds of accounts
// (e.g. SavingsAccount, CheckingAccount...)
trait Account {
private var balance: Long = 0
def availableBalance: Long = balance
def decreaseBalance(amount: Long) {
if (amount < 0)
throw new InsufficientFundsException
balance -= amount
}
def increaseBalance(amount: Long) {
balance += amount
}
def updateLog(msg: String, date: Date,
amount: Long) {
println("Account: " + toString + ", " + msg + ", "
+ date.toString + ", " + amount)
}
}// MoneySource is a methodless role type that captures // the form (interface) of part of the // Transfer behavior trait MoneySource { def transferTo(amount: Long, recipient: MoneySink) } // MoneySink is a methodless role type that captures // the form (interface) of the other part of the // Transfer behavior trait MoneySink { def increaseBalance(amount: Long) def updateLog(msg: String, date: Date, amount: Long) } // TransferMoneySink is the methodful role for the // recipient in a money transfer trait TransferMoneySink extends MoneySink { this: Account => def transferFrom(amount: Long, src: MoneySource) { increaseBalance(amount) updateLog("Transfer in", new Date, amount) } } class InsufficientFundsException extends RuntimeException // This is the methodful role for the source account // for the money transfer trait TransferMoneySource extends MoneySource { this: Account => // ...Read now
Unlock full access