Wednesday 7 January 2015

Static Method and Singlton in Scala

1. Scala has no static keyword. To define a static method:
  • Define your class and object in the same file, giving them the same name.
  • Define members that should appear to be “static” in the object.
  • Define nonstatic (instance) members in the class.
For example,

class Pizza (var crustType: String) { private val abc = 2
 override def toString = "Crust type is " + crustType
}

// companion object
object Pizza {
  val CRUST_TYPE_THIN = "thin"
  def double(foo: Pizza) = foo.abc * 2
  def getFoo = "Foo"
}

With the Pizza class and Pizza object defined in the same file (presumably named Pizza.scala), members of the Pizza object can be accessed just as static members of a Java class

2.  A class and its companion object can access each other’s private members

3. With CashRegister defined as an object, there can be only one instance of it. Because these methods are defined in an object instead of a class, they can be called in the same way as a static method in Java.


object CashRegister {
  def open { println("opened") }
  def close { println("closed") }
}

object Main extends App {
  CashRegister.open
  CashRegister.close
}

No comments:

Post a Comment