Simplified implementation of bank account:
scala> class bankaccount{ | Span style= "color: #0000ff;" >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
The BankAccount class defines the private variable bal, and three public methods: Balance returns the current balance; deposit adds the amount specified amount to the Bal Withdraw try to reduce the amount of the specified amount from the Bal and need to ensure that the balance after the operation cannot be negative. The return value of withdraw is a Boolean that indicates whether the requested funds were successfully extracted.
New= [email protected]scala> account deposit theScala> account Withdraw trueScala> account withdrawfalseScala>= 20
It is not only feasible but sometimes necessary to define getter and setter methods without associated fields.
class Thermometer { | var celsius:float = _ | def FAHRENHEIT = Celsius * 9/5 + | def fahren heit_= (f:float) { | celsius = (f-32) * 5/9 | } | override def toString = Fahrenheit + "f/" + Celsius + "C" | class Thermometer
The Celsius variable initialization is set to the default value '-', which specifies the "initialization value" of the variable. To be precise, the field initializer "=_" assigns a value of 0 to the field. The value of "0" here depends on the type of field. For a numeric type of 0, the Boolean type is false and the application type is null.
New= 32.0f/0. 0Cscala> T.celsius =100.0Scala>= 212.0f/ 0Cscala> T.fahrenheit = -40= -40.0Scala>= -40.0f/-40.0c
Scala Programming Chapter 18th Study notes-state-of-the-object