zoukankan      html  css  js  c++  java
  • 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 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
  • 相关阅读:
    vim高级编辑(一)
    [每日一题] 11gOCP 1z0-052 :2013-09-5 runInstaller oracle of no swap
    ABAP 中 Table Control例子
    跟我一起学习ASP.NET 4.5 MVC4.0(四)
    跟我一起学习ASP.NET 4.5 MVC4.0(三)
    跟我一起学习ASP.NET 4.5 MVC4.0(二)
    跟我一起学习ASP.NET 4.5 MVC4.0(一)
    如何选择Html.RenderPartial和Html.RenderAction
    ASP.NET MVC4 Razor
    ADO.NET Entity Framework -Code Fisrt 开篇(一)
  • 原文地址:https://www.cnblogs.com/gaopeng527/p/4190711.html
Copyright © 2011-2022 走看看