페이지

2015년 11월 2일 월요일

Scala2e Chapter4 Classes and Objects 4.1 Classes, fields, and methods

A class is a blueprint for objects.
Once you define a class, you can create objects from the class blueprint with the keyword new.

class ChecksumAccumulator{
// class definition goes here
}

You can create ChecksumAccumulator objects with:

new ChecksumAccumulator


class ChecksumAccumulator{
    var sum = 0
}

val acc = new ChecksumAccumulator
val csa = new ChecksumAccumulator



acc.sum = 3



An object's instance variables make up the memory image of the object.
You can see this illustrated here not only in that you see two sum variables, but also that when you changed on, the other was unaffected.


//Won't compile, because acc is a val
acc = new ChecksumAccumulator

class ChecksumAccumulator{
   private var sum = 0
}


val acc = new ChecksumAccumulator
acc.sum = 5 //Won't comile, because sum is private


The way you make members public in Scala is by not explicity specifying any access modifier.

class ChecksumAccumulator{

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

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


Ay parameers to a method can be used inside the method. 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 complie, becase b is a val
   sum += b
 }

The recommended style for methods is in fact to avoid having explicit, and especially multiple smaller ones. On the other hand, design choices depend on the design context, and Scala makes it easy to write methods that have multiple, explicit returns if that's what you desire.

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

Methods with a result type of Unit, such as ChecksumAccumulator's add method, are executed for their side effects.
A side effect is generally defined as mutating state somewhere external to the method or performing an I/O action.


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


One puzzler to watch out for is that whenever you leave off the equals sign before the body of a function, its result type will definitely be Unit.
This is true no matter what the body contains, because the Scala compiler can convert any type to Unit. For example, It the last result of a method is a String, but the method's result type is declared to be Unit, the String will be converted to Unit and its value lost.








댓글 없음: