环境: CentOS 6.3, eclipse
单例对象:类是指用class定义的scala 对象,如果用object替换class关键字,那么这个就叫单例对象,sigleton object, 单例对象不可以使用new 关键字生成新的对象实例下面使用三种使用校验和的方式来解释大家的疑问。
ChecksumAccumulator.scala //定义class(类) ChecksumAccumulator 和其伴生单例对象(object) ChecksumAccumulator
package scala import scala.collection.mutable.Map class ChecksumAccumulator { private var sum = 0; def add(b: Byte) = { sum += b } def checksum() = ~(sum & 0xFF) + 1 } object ChecksumAccumulator { private val cache = Map[String, Int]() def calculate(s: String) = { if (cache.contains(s)) { cache(s) // scala return value, not use return // wrong writing if "return cache(s)" } else { val acc = new ChecksumAccumulator() //val acc = new ChecksumAccumulator, it also work for (c <- s) { acc.add(c.toByte) } val cs = acc.checksum() cache += (s -> cs) cs } } }
ChecksumObject.scala // 单独定义 单例对象与上面的单例对象定义一样,只是名字不一样。 这里是为了说明单例对象可以和伴生类定义在通一个scala文件中,也可以单独定义在独立的文件中。
package scala import scala.collection.mutable.Map object ChecksumObject { private val cache = Map[String, Int]() def calculate(s: String) = { if (cache.contains(s)) { cache(s) // scala return value, not use return // wrong writing if "return cache(s)" } else { val acc = new ChecksumAccumulator() //val acc = new ChecksumAccumulator, it also work for (c <- s) { acc.add(c.toByte) } val cs = acc.checksum() cache += (s -> cs) cs } } }
调用校验和程序:
package scala import ChecksumAccumulator.calculate import ChecksumObject.calculate object Summer { def main(args:Array[String]){ for (arg <- args){ println(arg + "ChecksumAccumulator Object: " + ChecksumAccumulator.calculate(arg)) } for (arg <- args){ println(arg + "ChecksumObject Object: " + ChecksumObject.calculate(arg)) } println("direct use class:"+ getCheck("of")) } def getCheck(args:String) = { val ck = new ChecksumAccumulator() for (arg <- args){ ck.add(arg.toByte) } ck.checksum } }
运行结果:
of ChecksumAccumulator Object: -213
love ChecksumAccumulator Object: -182
of ChecksumObject Object: -213
love ChecksumObject Object: -182
of direct use class:-213
结论:
1.如果方法没有参数,调用时可以跟上(),也可以不写
2.scala 方法返回参数时,不能用return 字段,直接写上value 就可以
3. 没有相应的伴生class的单例对象叫孤立对象,Summer 以及ChecksumObject 都是孤立对象