Stateful Objects 有状态的对象
One normally describes the world as a set of objects, some of which have
state that changes over the course of time.
An object has a state if its behavior is influenced by its history.
一个对象是有状态的,如果它的行为受历史的影响
Example: a bank account has a state, because the answer to the question
“can I withdraw 100 CHF ?”
may vary over the course of the lifetime of the account
一个账户是有状态的,因为对问题:我能取100元吗?的回答在不同时候可能是不一样的
2.带有var的对象不一定是有状态的
def cons[T](hd: T, tl: => Stream[T]) = new Stream[T] { def head = hd private var tlOpt: Option[Stream[T]] = None def tail: T = tlOpt match { case Some(x) => x case None => tlOpt = Some(tl); tail } }
每次调用tail和head返回的结果是一样的
3.不带有var的对象不一定是没有状态的
class BankAccountProxy(ba: BankAccount) { def deposit(amount: Int): Unit = ba.deposit(amount) def withdraw(amount: Int): Int = ba.withdraw(amount) }