This is what I understood so far.
Classes should be used when we need to instantialte objects
We use "Objects" only when we have a singleton requirement meaning no need for multiple instances of "objects". I am thinking when we are building common library functions or utility functions in a project, we can use "objects" that way we need to instantiate each time we use methods/functions in that Object.
Case classes can be used when we want to save boilerplate code. Say we have "Stock" class. Each stock in general has hundreds of member variables. Instead of developer writing code for setters and getters, if we case class, it generates lot of default code.
Traits: don't know when to use. Both Traits and Objects don't take parameters during initialization.
Any more thoughts and ideas kindly share.
A class can extend another class, whereas a case class can not extend another case class (because it would not be possible to correctly implement their equality).
Some Benefits of Case Class/Object The one of the topmost benefit of Case Class is that Scala Compiler affix a method with the name of the class having identical number of parameters as defined in the class definition, because of that you can create objects of the Case Class even in the absence of the keyword new.
A companion object is an object with the same name as a class or trait and defined in the same source file as the associated file or trait.
Traits are used to share interfaces and fields between classes. They are similar to Java 8's interfaces. Classes and objects can extend traits, but traits cannot be instantiated and therefore have no parameters.
In Scala classes act like in any other OO-language (e.g. Java) too - that is you use classes to build objects (not Scala Objects) in your applications, which have a state (e.g. holding attributes, say a name of a Person).
Scala Objects are singletons. You use it in Scala mainly for
Case classes are intended to be used as lightweight classes (e.g. datacontainers). They are immutable by default and supposed to be structurally be compared (that is by comparing the values/state) and not by reference. Additionally, they provide features like serialization out of the box.
Traits are like interfaces in Java with some more features. They define the interface of a class/object.
Before you start to dive deeper in Scala, I'd recommend being first familiar with classic OO principles.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With