Friday, November 13, 2015

Scala Class and Object

class checksumAccumulator {

private var sum = 0

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

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

}


By default sum is public, we have to explicitly make it private.
Parameter b is by default val, so we cannot re-initialize it in checksum method, there is no return keyword, in such case, last value computed by method is returned - this is the recommended style - avoid explicit and multiple return statements

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

since our methods are just single statements, they can be written without {}, also when method does not return anything, i.e. its return type is Unit, we can skip writing the return type and "=", like in the add method

all datatypes can get converted to Unit - it simply looses the data
semicolon at the end of the statement are optional

object ChecksumAccumulator {
}

defining object instead of class gives singleton of the class called companion object class
A class and its companion object can access each other’s private members.

To run a Scala program, you must supply the name of a standalone singleton object with a main method that takes one parameter, an Array[String], and has a result type of Unit. Any singleton object with a main method of the proper signature can be used as the entry point into an application.

object Summer {
def main(args: Array[String]) {
}
}

We can also write the following:

object FallWinterSpringSummer extends Application {
}

No comments: