• Scala学习:类和对象


    一、类

    class ChecksumAccumulator {
      private var sum = 0
      def add(b:Byte):Unit = { sum += b }
      def checksum():Int = ~(sum & 0xFF) + 1
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • Scala中类、方法、成员变量都是默认public级别,不用声明
    • Scala中分号是可选的
    • Scala返回值类型是可选的,如上述eg中Unit和Int可以不用声明,Scala会做类型推断

    二、单例对象

    package Test
    
    import scala.collection.mutable
    
    class ChecksumAccumulator {
      private var sum = 0
      def add(b:Byte):Unit = { sum += b }
      def checksum():Int = ~(sum & 0xFF) + 1
    }
    
    object ChecksumAccumulator{
      private val cache = mutable.Map.empty[String,Int]
      def calculate(s:String):Int = {
        if (cache.contains(s))
          cache(s)
        else{
          val acc = new ChecksumAccumulator
          for (c <- s)
            acc.add(c.toByte)
          val cs = acc.checksum()
          cache += (s -> cs)
          cs
        }
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • Scala比Java更面向对象,其中一点就是Scala中不允许有静态成员
    • 但Scala提供了另一种形式-单例对象,就是上图中的object{}部分,当单例对象和某个类共用一个名字时,它被称为这个类的伴生对象,类也被称为单例对象的伴生类。必须在同一个源码文件中定义类和类的伴生对象
    • 类和伴生对象可以互相访问对方的私有成员
    • 没有同名的伴生类的单例对象被称为孤立对象,通常定义main方法,作为应用程序的入口
    • 此外,Java和Scala的一个重大区别是:Java要求将公共的类放入跟类同名的文件中,如若上述代码为Java代码,则文件名必须为ChecksumAccumulator.java,但Scala可以随意命名文件名,不过最好文件和类同名

    三、应用程序入口

    import Test.ChecksumAccumulator.calculate
    object SumTest  {
      def main(args:Array[String]) = {
        val str = "lishiming"
        println(calculate(str))
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • Scala同Java一样,应用程序的入口都在main方法中,scala的main方法定义在单例对象中
    import Test.ChecksumAccumulator.calculate
    
    object SumTest extends App {
      val str = "lishiming"
      println(calculate(str))
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 如上所示,scala提供了另一种应用程序的入口,不用编写main方法,只需在单例对象后extends
      App,然后把打算放在main方法中的代码直接写在单例对象后的花括号中即可
  • 相关阅读:
    go面试题 腐烂的苹果(橘子、水果)
    Basler相机Sdk采图的演示例程(C#)
    [Leetcode刷题] - 栅栏涂漆DP类问题
    Binder机制总结笔记
    文件上传漏洞(CVE-2022-23043)
    Vue轮播图
    面试(数据库的索引结构)
    BSV 上的付费解密智能合约
    怎么压缩图片大小?这些压缩方法值得收藏
    Nginx配置虚拟主机
  • 原文地址:https://blog.csdn.net/nzbing/article/details/126042289