Scala学习-类,对象 - webdancer's Blog


webdancer posted @ 2014年1月04日 01:39 in 编程语言 with tags scala , 4887 阅读


  • 属性:默认是public的,使用private可以改变作用域;
  • 方法:定义类的方法与定义普通的相同;Scala没有静态方法。
    class ChecksumAccumulator {
      private var sum = 0
      def add(b: Byte) { sum += b }
      def checksum(): Int = ~ (sum & 0xFF) + 1


  • class可以带参数,class Rational(a:Int,b:Int)
  • 使用override进行函数重载:
  • class Rational(a:Int,b:Int){
        overrride def toString = a + "/" + b
  • preconditions:可以使用require()。
class Rational(a:Int, b:Int){
	require(b != 0)
	val  numer:Int = a
	val  demon:Int = b
	override def toString = a + "/" + b
	def add(that: Rational) = new Rational(
		a * that.demon + b * that.numer,
		b * that.demon

2.使用object定义singleton 对象。

import scala.collection.mutable.Map

object ChecksumAccumulator {
  private val cache = Map[String, Int]()
  def calculate(s: String): Int =
    if (cache.contains(s))
    else {
      val acc = new ChecksumAccumulator
      for (c <- s)
      val cs = acc.checksum()
        cache += (s -> cs)

Singleton与class的名字相同,他们得放在同一源文件中,称为companion class 与companion object。不会创建新的类型;与class的名字不同,称为standalone对象,这种对象可以作为一个Scala程序的启动点。




也可是使用Application traits来启动程序,不过这种方法仅仅用在一些简单的,单线程程序中。


PAN India meaning 说:
2022年8月08日 19:58

PAN is abbreviated as Presence Across Nation and is operating or available at every possible location. A mark of PAN India is given to an organization or firm or company if their entity or branches are spread across every state and their customers can avail of their services from anywhere in India. PAN India meaning If any company operates at one location at the start and has spread its branches to various cities of India, then that company can use the recognition to announce its company growth.

GSEB STD-1 Model Pap 说:
2022年9月10日 21:55

Gujarat State Department of School Education, Gandhinagar and the State level subject experts and other private school teaching staff of the Elementary Level Primary School have designed and suggested the GSEB 1st Class Model Paper 2023 with sample answers Set wide as SET-A, SET-B, SET-C and SET-D to know the new exam scheme or question pattern. GSEB STD-1 Model Paper Students of the Gujarat state can download the NCERT & SCERT Syllabus GSEB STD-1 Question Paper 2023 Pdf with sample answers along with the class teacher’s suggested all lesson or chapter’s most important questions for Part-A, Part-B, Part-C and Part-D exams of Term-1 & Term-2 to the academic year of 2023.

seo service london 说:
2024年2月21日 02:00

Great post and amazing facts right here.Keep it up the wonderful work

登录 *

loading captcha image...
or Ctrl+Enter
Host by | Power by Chito 1.3.3 beta | © 2007 LinuxGem | Design by Matthew "Agent Spork" McGee