In Scala, an object can mean an instance of a class. Also, “object” can be used as a keyword.
Lets see usage of object as keyword in this article.
Singleton Object
A singleton is a class that can have only one instance.
We can use the object keyword to create a Singleton object as follows :
object Greeting { def greet{ println("Hello"); } }
With Greeting defined as an object, there can be only one instance of it. We can call its greet method using the class name as Greeting.greet
object HelloWorldScala { def main(args: Array[String]) { Greeting.greet; } }
Output:
Hello
Note:
- Scala does not have static members, like Java. Instead, an object is used to hold members that span instances, such as constants.
- Unlike classes, singleton objects cannot take parameter.
Companion Object
If an object and a class have the same name and are defined in the same file, they are called companions.
Companion objects and classes are considered a single unit in terms of access controls, so they can access each other’s private and protected fields and methods.
A companion object is an object that shares the same name and source file with another class or trait.
Example
We use a companion class Shape and a companion object Shape, which acts as a factory.
trait Shape { def area :Double } object Shape { private class Circle(radius: Double) extends Shape{ override val area = 3.14*radius*radius } private class Rectangle (height: Double, length: Double)extends Shape{ override val area = height * length } def apply(height :Double , length :Double ) : Shape = new Rectangle(height,length) def apply(radius :Double) : Shape = new Circle(radius) } object Main extends App { val circle = Shape(2) println(circle.area) val rectangle = Shape(2,3) println(rectangle.area) }
Note:
For case classes, the compiler automatically generates a companion object for you.
© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post