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.
- scala> abstract class SuperClass {
- | def method = "hi"
- | val value = 10
- | }
- defined class SuperClass
- scala> object MyObject extends SuperClass {
- | override def method = "Hello"
- | def anotherMethod = "other"
- | }
- defined module MyObject
- scala> MyObject.method
- res0: java.lang.String = Hello
- scala> MyObject.value
- res1: Int = 10
- scala> MyObject.anotherMethod
- res2: java.lang.String = other
Objects are also a good way to modularize projects. You can define classes and other objects within an object
- scala> object Outer {
- | case class Data(name:String)
- |
- | def print(data:Data) = Console.println(data.name)
- |
- | object Factory {
- | def defaultData = Data("defaultName")
- | }
- | }
- defined module Outer
- scala> val data = Outer.Factory.defaultData
- data: Outer.Data = Data(defaultName)
- scala> Outer.print(data)
- defaultName
No comments:
Post a Comment