Classes and Objects

1 定义类

class ChecksumAccumulator {
    var sum = 0 // field

    private var psum = 0 // private field 私有
}

创建对象:

var acc = new ChecksumAccumulator
acc.psum = 5 // 不会编译

Public 是 Scala 的默认访问级别

class ChecksumAccumulator {
    private var sum = 0

    def add(b: Byte): Unit = {
        sum += b
    }

    def checkSum(): Int = {
        return ~(sum & 0xFF) + 1
    }
}

One important characteristic of method parameters in Scala is that they are vals, not vars.

def add(b: Byte): Unit = {
    b = 1 // This won't compile, because b is a val
    sum += b
}

For the utmost in conciseness, you can leave off the result type and Scala will infer it. Will these changes, class ChecksumAccumulator looks like this:

class ChecksumAccumulator {
    private var sum = 0
    def add(b: Byte) = sum += b
    def checksum() = ~(sum & 0xFF) + 1
}

Although the Scala compiler will correctly infer the result types of the add and checksummethods shown in the previous example, readers of the code will also need to mentally inferthe result types by studying the bodies of the methods. As a result it is often better to explicitly provide the result types of public methods declared in a class even when the compiler would infer it for you:

class ChecksumAccumulator {
    private var sum = 0
    def add(b: Byte): Unit = sum += b
    def checksum(): Int = ~(sum & 0xFF) + 1
}

2 Semicolon Inference

a semicolon is required if you write multiple statements on a single line:

val s = "hello"; println(s)

3 Singletion Objects

companion class of the singleton object. A class and its companion object can access each other's private members.

import scala.collection.scala

object ChecksumAccumulator {
    private val cache = mutable.Map.empty[String, Int] // a mutable Map

    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 // ensures the checksum is the result of the method
        }
}

If you are a Java programmer, one way to think of singleton objects is as the home for any static methods you might have written in Java.

4 A scala application

scalac ChecksumAccumulator.scala Summer.scala

This compiles your source files, but there may be a perceptible delay before the compilation finishes. The reason is that every time the compiler starts up, it spends time scanning the contents of jar files and doing other initial work before it even looks at the fresh source files you submit to it. For this reason, the Scala distribution also includes a Scala ocmpilerdaemon called fcs (for fast Scala compiler).

fsc ChecksumAccumulator.scala Summer.scala

5 The App Trait

Scala provides a trait, scala.App

import ChecksumAccumulator.calculate

object FallWinterSprintSummer extends App {
    for (season <- List("fall", "winter", "spring"))
        println(season + ": " + calculate(season))
}
  1. extends App
  2. Instead of writing a main method, you place the code you would have put in the main method directly between the curly braces of the singleton object.

results matching ""

    No results matching ""