Scala Programming Chapter 18th Study notes-state-of-the-object

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.