More On Scala object
More on Scala object
We have seen how we can create singletons and companion objects using object
. In this notebook we introduce more things we can do with object
.
An object
can extend one class. However, it can extend one or more trait
s [1]. This results in an object that has all of the
features specified in the object definition [1]. One utilization of this pattern is to specify default objects as shown below.
abstract class Element(val idx: Int){
def nFaces: Int;
def nVertices: Int;
}
object DummyElement extends Element(-1){
override def nFaces: Int = -1
override def nVertices: Int = -1
}
Whenever we want to use an Element
that makes no sense but anyway it is needed we can use DummyElement
.
Just like Java and C++, a Scala application starts with a main
method which has the following signature [1]
def main(args: Array[String]): Unit
We can wrap that in a companion object
class Hello{
def showMsg() = println("Hello...")
}
object Hello{
def main(args: Array[String]){
val msg = new Hello
msg.showMsg()
}
}
Note that we can also extend the App
trait and place the program code into the constructor body [1].
- Cay Horstmann,
Scala for the Impatient 1st Edition