银行账号的简化实现:
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 BankAccount account: BankAccount = BankAccount@18532dc scala> account deposit 100 scala> account withdraw 80 res1: Boolean = true scala> account withdraw 80 res2: Boolean = false scala> account.balance res3: 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 Thermometer t: Thermometer = 32.0F/0.0C scala> t.celsius = 100 t.celsius: Float = 100.0 scala> t res0: Thermometer = 212.0F/100.0C scala> t.fahrenheit = -40 t.fahrenheit: Float = -40.0 scala> t res1: Thermometer = -40.0F/-40.0C