Classes, Instances, Objects, Companion Object, Scala Application
November 26, 2019 Leave a comment
Class in scala is used to wrap instance level functionality.
class Foo //class
Instance
val foo = new Foo // instance
Note: In scala, we do not call instance of a class as an Object because Object has a special meaning.
Object Scala Object is a Singleton Instance by definition.
SCALA DOES NOT HAVE CLASS LEVEL FUNCTIONALITY (like “static” in java) – Equivalet in scala is Object
Everytime an object is defined, this object will be of its own type (“type person”) and it itself is the only instance.
Objects can be defined in a similar way to that of the classes with the only difference being the constructor parameters.
object Person { val N_HANDS = 2 // static in java } val person1 = Person // refers to the only instance on Object val person2 = Person println(person1 == person2) // returns true
Companion Object
We can define class with the same name as that of object to seperate instance level functionality (Class) from static/class level functionality (Object), and when class and object exists with same name in one file, they are called COMPANION OBJECTS or COMPANIONS
object Person { val N_HANDS = 2 // static in java } class Person(name: String, val age: Int) { // where as name and age are instance specific and hence they are referred in class members }
Note:
In Java we access static member via class name and instance member via object reference
But in Scala, we access class level memebers via Object and instance level members via the instance of a Class, It turns out to be more Object Oriented than JAVA eventhough its created for functional programming
Scala Application
When a scala object inherts scala.App trait it becomes scala application. The App trait can be used to quickly turn objects into executable programs.
object Main extends App { Console.println("Hello World: " + (args mkString ", ")) }
Recent Comments