首页 > 代码库 > scala编程第18章学习笔记——有状态的对象

scala编程第18章学习笔记——有状态的对象

银行账号的简化实现:

scala> class BankAccount{     | private var bal: Int = 0     | def balance: Int = bal     | def deposit(amount: Int) {     | require(amount > 0)     | bal += amount     | }     |     | def withdraw(amount: Int): Boolean =     | if (amount > bal) false     | else{     | bal -= amount     | true     | }     | }defined class BankAccount

BankAccount类定义了私有变量bal,以及三个公开的方法:balance返回当前余额;deposit向bal添加指定amount的金额;withdraw尝试从bal减少指定amount的金额并须要确保操作之后的余额不能变为负数。withdraw的返回值为Boolean类型,说明请求的资金是否被成功提取。

scala> val account = new BankAccountaccount: BankAccount = BankAccount@18532dcscala> account deposit 100scala> account withdraw 80res1: Boolean = truescala> account withdraw 80res2: Boolean = falsescala> account.balanceres3: Int = 20

 只定义getter和setter方法而不带有关联字段,这种做法不但可行,有时甚至很有必要。

scala> class Thermometer {     | var celsius: Float = _     | def fahrenheit = celsius * 9 / 5 + 32     | def fahrenheit_= (f: Float) {     | celsius = (f - 32) * 5 / 9     | }     | override def toString = fahrenheit + "F/" + celsius + "C"     | }defined class Thermometer

celsius变量初始化设置为缺省值‘—‘,这个符号指定了变量的”初始化值“。精确的说,字段的初始化器”=_”把零值赋给该字段。这里的“零”的取值取决于字段的类型。对于数值类型来说是0,布尔类型是false,应用类型则是null。

scala> val t = new Thermometert: Thermometer = 32.0F/0.0Cscala> t.celsius = 100t.celsius: Float = 100.0scala> tres0: Thermometer = 212.0F/100.0Cscala> t.fahrenheit = -40t.fahrenheit: Float = -40.0scala> tres1: Thermometer = -40.0F/-40.0C

scala编程第18章学习笔记——有状态的对象