Thursday, August 20, 2009

Object

Scala does not have static methods in the same way that Java does. As a replacement Scala has "objects" and object is a singleton object whose methods can be called in the same manner one would call a static method in Java. The big differentiator is that objects are complete objects and can extent abstract classes and traits.

Objects are sometime referred to as modules as well. See next section for more on modules. In addition there is a special situation where a class has what is called a companion object. That is a topic for another day. Finally you can have case objects, also a topic for another day. case objects will be address as part of the Enumeration topic.
  1. scala> abstract class SuperClass {
  2.     | def method = "hi"
  3.     | val value = 10
  4.     | }
  5. defined class SuperClass
  6. scala>object MyObject extends SuperClass {
  7.     | overridedef method = "Hello"
  8.     | def anotherMethod = "other"
  9.     | }
  10. defined module MyObject
  11. scala> MyObject.method
  12. res0: java.lang.String = Hello
  13. scala> MyObject.value
  14. res1: Int = 10
  15. scala> MyObject.anotherMethod
  16. res2: java.lang.String = other

Objects are also a good way to modularize projects. You can define classes and other objects within an object
  1. scala>object Outer {
  2.     | caseclass Data(name:String)
  3.     |
  4.     | def print(data:Data) = Console.println(data.name)
  5.     |
  6.     | object Factory {
  7.     | def defaultData = Data("defaultName")
  8.     | }
  9.     | }
  10. defined module Outer
  11. scala>val data = Outer.Factory.defaultData
  12. data: Outer.Data = Data(defaultName)
  13. scala> Outer.print(data)
  14. defaultName

No comments:

Post a Comment