Created
November 23, 2011 11:56
-
-
Save bcambel/1388508 to your computer and use it in GitHub Desktop.
Introduction to Scala
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
| //def <function name>(<parameter-name>:<parameter-type){ | |
| def changingBalance(account:Account){ | |
| println("======Starting balance :" + account.balance) | |
| println("Depositing $10.0") | |
| account.deposit(10.0d) | |
| println("new balance:" + account.balance) | |
| println("Withdrawing $5.00") | |
| account.withdraw(5.0) | |
| println("New balance is "+ account.balance) | |
| } | |
| println("Hello world!") | |
| var a = new Account(0) | |
| changingBalance(a) | |
| var oa = new ObservedAccount(0) | |
| changingBalance(oa) | |
| oa.addObserver(new AccountReporter) | |
| changingBalance(oa) | |
| trait Observer[S]{ | |
| def receiveUpdate(subject:S) | |
| } | |
| trait Subject[S]{ | |
| this : S => | |
| private var observers: List[Observer[S]] = Nil | |
| def addObserver(observer: Observer[S]) = observers = observer :: observers | |
| // smart iterator block with "_" | |
| // if we were in ruby observers.each { |o| o.receiveUpdate(self) } | |
| def notifyObservers() = observers.foreach(_.receiveUpdate(this)) | |
| } | |
| class Account(initialBalance: Double){ | |
| private var currentBalance = initialBalance | |
| def balance = currentBalance | |
| def deposit(amount:Double) = currentBalance += amount | |
| def withdraw(amount:Double) = currentBalance -= amount | |
| } | |
| // With keyword enables extended inheritance | |
| // So I assume that is a combination of Interface + Inheritance | |
| class ObservedAccount(initialBalance:Double) extends Account(initialBalance) with Subject[Account]{ | |
| override def deposit(amount:Double) = { | |
| super.deposit(amount) | |
| notifyObservers() | |
| } | |
| override def withdraw(amount:Double) = { | |
| super.withdraw(amount) | |
| notifyObservers() | |
| } | |
| } | |
| class AccountReporter extends Observer[Account]{ | |
| def receiveUpdate(account:Account) = println("Observed balance change:" + account.balance) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment