In Scala what is the reason that you don't need to use "new" to create a new "case class"? I tried searching for awhile now without answers.
Case class constructor parameters are public val fields by default, so accessor methods are generated for each parameter. An apply method is created in the companion object of the class, so you don't need to use the new keyword to create a new instance of the class.
Scala case classes are just regular classes which are immutable by default and decomposable through pattern matching. It uses equal method to compare instance structurally. It does not use new keyword to instantiate object. All the parameters listed in the case class are public and immutable by default.
An object can extend another class, making its fields and methods available in a global instance. The reverse is not true, however, because an object cannot itself be extended.
A Scala Case Class is like a regular class, except it is good for modeling immutable data. It also serves useful in pattern matching, such a class has a default apply() method which handles object construction. A scala case class also has all vals, which means they are immutable.
Do you want the how or the why? As the other answer notes, the how is just the apply
method on the automatically generated companion object.
For the why: case classes are often used to implement algebraic data types in Scala, and the new
-less constructor allows code that is more elegant (creating a value looks more like deconstructing it via pattern matching, for example) and that more closely resembles ADT syntax in other languages.
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